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
endIn 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)