Rails habtm回调

时间:2011-03-11 02:34:03

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

有没有办法在项目添加到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回调,因为连接表没有模型(因为它是真的HABTM)。

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

1 个答案:

答案 0 :(得分:33)

是的,有:

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