Last Updated: February 25, 2016
·
4.079K
· olancheg

`after_commit` in ActiveRecord::Observer

after_commit method in ActiveRecord::Base can have some conditional options, that ActiveRecord::Observer can't have

class User < ActiveRecord::Base
  after_commit :do_something, on: :create
  def do_something
    # ...
  end
end

to move that callback to Observer you should use method transaction_include_action?.

class UserObserver < ActiveRecord::Observer
  def after_commit(user)
    if user.send(:transaction_include_action?, :create)
      # ...
    end
  end
end

Note: you should call method with send, because it's protected

2 Responses
Add your response

Oh, thanks! That's what I'm looking for!

over 1 year ago ·

thanks! but i'm curious about is it the only possible way to do this? it seems to be

over 1 year ago ·