gpt4 book ai didi

ruby-on-rails - 为 has_many 或 habtm 动态创建 after_add 和 after_remove 回调?

转载 作者:行者123 更新时间:2023-12-04 07:36:44 25 4
gpt4 key购买 nike

有没有办法动态添加after_addafter_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只是一个类方法。

最佳答案

最简单的是

User.after_add_for_things << lambda do |user, thing| 
Rails.logger.info "#{thing} added to #{user}"
end
注意:不再适用于 Rails 7(感谢 Andrew Hodgkinson 指出这一点)

关于ruby-on-rails - 为 has_many 或 habtm 动态创建 after_add 和 after_remove 回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8978853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com