Dynamically create after_add and after_remove callbacks for has_many or habtm?

寵の児 提交于 2019-12-04 04:42:24

The easiest would be

User.after_add_for_things << lambda do |user, thing| 
  Rails.logger.info "#{thing} added to #{user}"
end

I was able to come up with the following by using 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!