【问题标题】:Rails habtm callbacksRails habtm 回调
【发布时间】:2011-03-11 02:34:03
【问题描述】:

有没有办法在将项目添加到 habtm 关系时添加回调?

比如我有以下两个模型,UserRole

# user.rb
class User; has_and_belongs_to_many :roles; end

 

# role.rb
class Role; has_and_belongs_to_many :users; end

我想为<< 方法(@user << @role)添加回调,但我似乎找不到 ActiveRecord 回调,因为连接表没有模型(因为它是一个真正的习惯)。

我知道我可以编写像add_to_role(role) 这样的方法,并在其中定义所有内容,但我更喜欢使用回调。这可能吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 has-and-belongs-to-many


    【解决方案1】:

    是的,有:

    class User < AR::Base
      has_and_belongs_to_many :roles, 
        :after_add => :tweet_promotion, 
        :after_remove => :drink_self_stupid
    
    private
    
      def tweet_promotion
        # ...
      end
    
      def drink_self_stupid
        # ...
      end
    end
    

    在此页面上查找“关联回调”以了解更多信息: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

    【讨论】:

    • 我在关系的哪一侧添加回调是否重要,还是一样??
    • 我刚刚在 Rails 3.2.8 上试过这个,很遗憾,在哪一边添加这些回调。你的经验是什么?
    • 对于现在遇到这个问题的人来说,是的,这很重要。这就是我掉进去的陷阱。看这个答案了解stackoverflow.com/questions/56951926/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多