- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在阅读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
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_add
和after_add
回调。与是否将记录保存到数据库无关。 (对于has_and_belongs_to_many
和has_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/
我有两个 ActiveRecord 模型,彼此之间具有 HABTM 关系。当我通过允许通过选中复选框添加区域的表单添加 AccessUnit 时,我收到一个异常,即 AccessUnitUpdater
这似乎是 has_many 和 has_one 之间的不一致。 has_many 关联允许您指定一个 after_add 回调,该回调在将对象添加到集合后调用。 class Person has_
我正在阅读Rails 3 Way的书,并感到困惑: :after_add => callback Called after a record is added to the collection vi
我有以下型号: class Review :voteable, :after_add => :sum_votes, :after_remove => :sum_votes def
有没有办法动态添加after_add和 after_remove对现有 has_many 的回调或 has_and_belongs_to_many关系? 例如,假设我有模型 User , Thing
我有一个 Person 类,其中 HABTM Preferences - 当添加或删除首选项时,我需要调用一个方法来通知第三方 API。 现在我的 person 类是这样的: class Person
我是一名优秀的程序员,十分优秀!