f5-vlq
Last Updated: February 25, 2016
·
3.175K
· olancheg
9755f712108cec98056e9dd7d0109441

`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

Say Thanks
Respond

2 Responses
Add your response

625
C24ce8d41d4134d3d616fbd486162c38

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

over 1 year ago ·
15620
0e8a012c6542299bec2bc94922a3ed27

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

over 1 year ago ·