gpt4 book ai didi

ruby-on-rails - has_many和:after_add/:before_add => callback for << and create methods

转载 作者:行者123 更新时间:2023-12-05 01:20:54 35 4
gpt4 key购买 nike

我正在阅读Rails 3 Way的书,并感到困惑:

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



据我了解book.chapters.create(title:'第一章')不会调用before_add回调,但实际上它正在调用。
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

在控制台中(最小)
 > b = Book.first
Book Load (0.1ms) SELECT "books".* FROM "books" LIMIT 1
> b.chapters.create(title: 'Last Chapter')
begin transaction
chapter added to book
INSERT INTO "chapters" ....
commit transaction

在这里,您可以看到 after_add回调是为 create调用的。

我误会了吗?

编辑
b.chapters.new(title: 'New Chapter')
b.chapters.build(title: 'New Chapter')

也调用回调

最佳答案

将项目添加到集合时,将触发before_addafter_add回调。与是否将记录保存到数据库无关。 (对于has_and_belongs_to_manyhas_many :through关系,这里会有一点异常(exception),其中将其添加到集合中会立即由ActiveRecord在内部反射(reflect)到数据库中)。

将新记录添加到集合后,将触发回调。在将元素添加到集合之前,将调用before_add,在之后将after_add调用。

下面的示例可以使您更好地理解。

# id: integer
class Author < ActiveRecord::Base
has_many :books, before_add: :bef, after_add: aft

def bef
puts "Before adding, author ##{id} has #{books.size} books"
end

def aft
puts "After adding, author ##{id} has #{books.size} books"
end
end

# id integer
# author_id: integer
class Book < ActiveRecord::Base
belongs_to :author
after_save: :saved

def saved
puts "The book is now saved!"
end
end

> book = Book.new

> author = Author.first

> author.books << book
'Before adding, author #1 has 3 books'
'After adding, author #1 has 4 books'

> author.save
'The book is now saved'

关于ruby-on-rails - has_many和:after_add/:before_add => callback for << and create methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12511792/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com