所以我的应用程序中有代码附加到与“<<”运算符的 has_many 关系,如下所示:
class BlogPost < ActiveRecord::Base
has_many :comments
def add_comment(content)
@new_comment = Comment.create(content)
self.comments << @new_comment
end
end
而且它似乎有效。我从来没有真正质疑过它或想知道它何时调用“保存”(我想我从来没有深刻理解何时开始调用“保存”)。
但是,似乎 after_save
在我的 add_comment
中没有激活评论 Hook 功能,提示我问:
如何<<
运算符(operator)在 activerecord 中工作,我在哪里可以阅读更多相关信息?
谢谢
最佳答案
当您使用 shovel
运算符 ( <<
),Rails 会自动保存关联的对象。所以,当你这样做时:
self.comments << @new_comment
@new_comment
被添加到 comments
收集并立即触发更新 SQL,而无需等待对父对象的保存或更新调用,除非父对象是新记录。
collection<<(object, …) Adds one or more objects to the collection by creating associations in the join table (collection.push and collection.concat are aliases to this method). Note that this operation instantly fires update SQL without waiting for the save or update call on the parent object, unless the parent object is a new record.
关于ruby-on-rails - Rails ActiveRecord Shovel (<<) 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32941230/