views:

26

answers:

3

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 practices 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.

+3  A: 

It might be best to set up an observer, something like "FirstObserver" and write an after-save callback there.

vegetables
Indeed, observer is solution to my problem, I didn't know about their existence, thanks.
skrat
+3  A: 

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
buru
A: 

Try this one:

First.class_eval do
  def after_save record
     #mashrooooms
  end
end
fantactuka