Search code examples
ruby-on-railsruby-on-rails-3has-and-belongs-to-many

Rails habtm callbacks


Is there a way to add callbacks for when an item is added to a habtm relationship?

For example, I have the following two models, User and Role:

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

 

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

I want to add a callback to the << method (@user << @role), but I can't seem to find an ActiveRecord callback because there is no model for the join table (because its a true habtm).

I'm aware that I could write a method like add_to_role(role), and define everything in there, but I'd prefer to use a callback. Is this possible?


Solution

  • Yes there is:

    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
    

    Look for 'Association callbacks' on this page for more: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html