How to identify newly added has_many association in rails after_commit

Viewed 289

Have below association in author class

has_many :books,
class_name :"Learning::Books",
through: :elearning,
dependent: :destroy

with after_commit as,

after_commit :any_book_added?, on: :update

def any_book_added?
     book = books.select { |book| book.previous_changes.key?('id') }
     # book's previous_changes is always empty hash even when newly added
end

Unable to find the newly added association with this method. Is this due to class_name?

1 Answers

Rails has a couple methods that might help you, before_add and after_add

Using this, you can define a method to set an instance variable to true

class Author < ApplicationRecord
  has_many :books, through: :elearning, after_add: :new_book_added

  def any_book_added?
    @new_book_added 
  end

  private

  def new_book_added
    @new_book_added = true
  end
end

Then when you add a book to an author, the new_book_added method will be called and you can at any future time ask your Author class if any_book_added?

i.e.

author = Author.last
author.any_book_added?
=> false
author.books = [Book.new]
author.any_book_added?
=> true

As you can see, the callback method new_book_added can accept the book that has been added as well so you can save that information.

Related