Есть ли способ динамически добавлять обратные вызовы after_add
и after_remove
к существующим has_many
или has_and_belongs_to_many
отношения?
Например, предположим, что у меня есть модели User
, Thing
и модель соединения UserThingRelationship
, а модель User
выглядит примерно так:
class User < ActiveRecord::Base
has_many :user_thing_relationships
has_many :things, :through => :user_thing_relationships
end
Я хотел бы иметь возможность в модуле, расширяющем User
, добавить : after_add
и : after_remove
обратные вызовы для отношения User.has_many (: things, ...)
. То есть, иметь что-то вроде
module DoesAwesomeStuff
def does_awesome_stuff relationship, callback
# or however this can be achieved...
after_add(relationship) callback
after_remove(relationship) callback
end
end
, чтобы
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
фактически было таким же, как
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
. Это можно сделать довольно эффективно для добавления after_save
и т. Д. Обратных вызовов в расширяемую модель, поскольку ActiveRecord :: Base # after_save
- это просто метод класса.