Rails habtm回调

set*_*rgo 22 ruby-on-rails has-and-belongs-to-many ruby-on-rails-3

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

例如,我有以下两个模型,User并且Role:

# user.rb
class User; has_and_belongs_to_many :roles; end
Run Code Online (Sandbox Code Playgroud)

 

# role.rb
class Role; has_and_belongs_to_many :users; end
Run Code Online (Sandbox Code Playgroud)

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

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

Ala*_*ody 34

就在这里:

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
Run Code Online (Sandbox Code Playgroud)

在此页面上查找"协会回调"以获取更多信息:http: //api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html