Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails habtm callbacks

Tags:

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?

like image 438
sethvargo Avatar asked Mar 11 '11 02:03

sethvargo


People also ask

How do Rails callbacks work?

Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.

What is controller callback in Rails?

A callback allows you to run some code (usually a method) automatically when another piece of code runs. In Rails, you'll commonly see callbacks that run before, after or even around other bits of code. Callback functions are minimizing the length of codes in controllers.

What is commit in Rails?

The after_commit callback is a well-known part of the Ruby on Rails framework. It's called after a record has been created, updated, or destroyed and after the corresponding database transaction has been commited. It's the primary method to use if we want to trigger a background job associated with a record.


1 Answers

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

like image 172
Alan Peabody Avatar answered Nov 28 '22 03:11

Alan Peabody