ActiveRecord callback setup from different model
Let's say I have to simple models First
and Second
, and there is one to one relationship from Second
using belongs_to :first
. Now I want to do something with Second
, when First
is saved. But I don't want to setup an after_save
callback in First
, to deal with Second
.
I want to keep my models clean, and unaware of each other as much as possible. I'm always following best practice开发者_StackOverflow中文版s in object encapsulation, and it makes my life easier, always.
So naturally, since after_save
is a class method, I tried to setup this callback in Second
, like this:
class Second < ActiveRecord::Base
belongs_to :first
First.after_save do |record|
if that = Second.find_by_first_id(record.id)
# grow magic mushrooms here...
end
end
end
but this doesn't work, that callback is never executed, and no error is raised.
You may do it via observer:
class FirstObserver < ActiveRecord::Observer
def after_save(first)
...
end
end
Don't forget to enable observer in your config/application.rb
:
config.active_record.observers = :first_observer
It might be best to set up an observer, something like "FirstObserver" and write an after-save callback there.
Try this one:
First.class_eval do
def after_save record
#mashrooooms
end
end
精彩评论