Topic: has_many and :after_add / :before_add => callback for << and create

I am reading Rails 3 Way book and got confused at the point:

:after_add => callback Called after a record is added to the collection via the << method. Is not triggered by the collection’s create method

As I understand

book.chapters.create(title: 'First Chapter')

won't invoke before_add callback but actually it is calling.

class Book < ActiveRecord::Base
  attr_accessible :title
  has_many :chapters, :before_add => :add_chapter

  private
    def add_chapter(chapter)
      logger.error('chapter added to book')
    end
end

class Chapter < ActiveRecord::Base
  belongs_to :book
  attr_accessible :title
end

In Console(minified)

 > b = Book.first
  SELECT "books".* FROM "books"...
 > b.chapters.create(title: 'Last Chapter')
 chapter added to book
  INSERT INTO "chapters" ....

Here you can see that after_add callback is invoke for create.

Not only create but new and build also invokes callback

Am I misunderstood something or reading some outdate content which change later?

Last edited by amit.savani (2012-09-20 09:23:10)

Re: has_many and :after_add / :before_add => callback for << and create

Because you are calling the methods omn the parent object the parent is adding the child that you create to it;s array of chuldren for you and that therefore triggers the events. Hope that makes sense

What you want and what you need are too often not the same thing!
When your head is hurting from trying to solve a problem, stop standing on it. When you are the right way up you will see the problem differently and you just might find the solution.
(Quote by me 15th July 2009)