为has_many或habtm动态创建after_add和after_remove回调? [英] Dynamically create after_add and after_remove callbacks for has_many or habtm?
问题描述
有没有办法动态添加 after_add
和 after_remove
回调到现有的 has_many c
Is there a way to dynamically add after_add
and after_remove
callbacks to an existing has_many
or has_and_belongs_to_many
relationship?
例如,假设我有模型 User
, Thing
和一个连接模型 UserThingRelationship
$ c> User 模型是这样的:
For example, suppose I have models User
, Thing
, and a join model UserThingRelationship
, and the User
model is something like this:
class User < ActiveRecord::Base
has_many :user_thing_relationships
has_many :things, :through => :user_thing_relationships
end
我想能够在一个扩展的模块中用户
,添加:after_add
和:after_remove
User.has_many(:things,...)
关系。 Ie,有类似
I'd like to be able to, in a module that extends User
, add :after_add
and :after_remove
callbacks to the User.has_many(:things, ...)
relationship. I.e., have something like
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
只是一个类方法。
This can be done pretty effectively for adding after_save
, etc, callbacks to the model that's being extended, since ActiveRecord::Base#after_save
is just a class method.
推荐答案
我能够通过使用 ActiveRecord :: Reflection :
module AfterAdd
def after_add rel, callback
a = reflect_on_association(rel)
send(a.macro, rel, a.options.merge(:after_add => callback))
end
end
class User < ActiveRecord::Base
extend AfterAdd
has_many :user_thing_relationships
has_many :things, :through => :user_thing_relationships
after_add :things, :my_callback
def my_callback
puts "Hello"
end
end
我不想回答我自己的问题,所以如果有人能想出在未来几天更好的解决方案。
I don't want to answer my own question, so I won't give myself answer credit if someone else can come up with a better solution in the next few days.
这篇关于为has_many或habtm动态创建after_add和after_remove回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!