【发布时间】:2012-02-17 05:29:18
【问题描述】:
有没有办法将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 只是一个类方法。
【问题讨论】:
标签: ruby-on-rails activerecord callback has-many-through