0

What is the best way in rails to implement the situation where when Model A is created, Model B can observe this and change.

One solution is some kind of filter such as an after_create in Model A. However having some Model B code in Model A seems like a bad practise.

Another solution is to have some code in Model B's controller to handle this which also seems like a bad idea.

Ideally Model B or some kind of independent observer class should be able to observe the creation of all Model A's and then act as required.

TrevTheDev
  • 2,616
  • 2
  • 18
  • 36

1 Answers1

1

Update:

Thanks to OP for pointing out that this was for Rails4 as the question was originally tagged which I had missed to notice. Rails 4 alternative to Observers question here at SO has several great answers.

Original Answer:

This can be done using Observer. Say you want a ModelAObserver, where you'd define the operations required on ModelB, you can create a new file app/models/model_a_observer.rb manually or use the generator rails g observer ModelA.

Then define the required callbacks in the ModelAObserver:

# app/models/model_a_observer.rb
class ModelAObserver < ActiveRecord::Observer
   observe :model_a

   def after_create(new_model_a_record)
     ...
     # Operations on ModelB
     ...
   end
end 
Community
  • 1
  • 1
vee
  • 38,255
  • 7
  • 74
  • 78
  • Thank you that help me. I'm using rails 4 in which observers have been deprecated, but your answer led me to this: http://stackoverflow.com/questions/15165260/rails-observer-alternatives-for-4-0 – TrevTheDev Dec 23 '13 at 07:17
  • @user3091013, thanks for the link. I've added a short note at the top of this answer with the link you posted. – vee Dec 23 '13 at 07:28