Is there a way to dynamically add after_add and after_remove to existing has_many or has_and_belongs_to_many ?
For example, suppose I have a User , Thing model, and a UserThingRelationship join UserThingRelationship , and the User model looks something like this:
class User < ActiveRecord::Base has_many :user_thing_relationships has_many :things, :through => :user_thing_relationships end
I would like to be able in the module that extends User to add :after_add and :after_remove callbacks to the relation User.has_many(:things, ...) . Ie have something like
module DoesAwesomeStuff def does_awesome_stuff relationship, callback
So,
class User < ActiveRecord::Base has_many :user_thing_relationships has_many :things, :through => :user_thing_relationships does_awesome_stuff :things, :my_callback def my_callback; puts "awesome"; end end
It is actually the same as
class User < ActiveRecord::Base has_many :user_thing_relationships has_many :things, :through => :user_thing_relationships, :after_add => :my_callback, :after_remove => :my_callback def my_callback; puts "awesome"; end end
This can be done quite efficiently for adding after_save , etc. callbacks to the extensible model, since ActiveRecord::Base#after_save is just a class method.
source share