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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With