I have a Rails model that has a belongs_to relationship to another model.
class Foo < ActiveRecord::Base
belongs_to :bar
end
Every time a bar is set / updated on the foo I want “intercept” the modification of that change and update something on the foo.
My guess is that I can just override the setter for bar and do what I want. But, since I’m relatively new to Ruby / Rails, my concern is that there are “magical” ways that the bar can get set on the foo that don’t go through my setter (perhaps with mass-assignment, update/update_all calls, etc).
What is the safest way to ensure that any change to bar runs a block of code that reacts to that change?
Depending on your needs, you can use callbacks on your bar to execute specific code on your foo.
All the documentation you need is here http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
For example :