skrat
skrat

Reputation: 5562

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

Upvotes: 1

Views: 206

Answers (3)

fantactuka
fantactuka

Reputation: 3334

Try this one:

First.class_eval do
  def after_save record
     #mashrooooms
  end
end

Upvotes: 0

buru
buru

Reputation: 3210

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

Upvotes: 4

venables
venables

Reputation: 2594

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

Upvotes: 3

Related Questions