Very Important in Associations Callbacks

4.5 Association Callbacks

Normal callbacks hook into the life cycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a :before_save callback to cause something to happen just before an object is saved.

Association callbacks are similar to normal callbacks, but they are triggered by events in the life cycle of a collection. There are four available association callbacks:

  • before_add
  • after_add
  • before_remove
  • after_remove

You define association callbacks by adding options to the association declaration. For example:

class Author < ApplicationRecord
  has_many :books, before_add: :check_credit_limit
 
  def check_credit_limit(book)
    ...
  end
end

Rails passes the object being added or removed to the callback.

You can stack callbacks on a single event by passing them as an array:

class Author < ApplicationRecord
  has_many :books,
    before_add: [:check_credit_limit, :calculate_shipping_charges]
 
  def check_credit_limit(book)
    ...
  end
 
  def calculate_shipping_charges(book)
    ...
  end
end

If a before_add callback throws an exception, the object does not get added to the collection. Similarly, if a before_remove callback throws an exception, the object does not get removed from the collection.

These callbacks are called only when the associated objects are added or removed through the association collection:

# Triggers `before_add` callback
author.books << book
author.books = [book, book2]
 
# Does not trigger the `before_add` callback
book.update(author_id: 1)

Comments

Popular posts from this blog

Rails 7 Features :: Comparison with Rails 6 and Rails 5