ruby-on-rails – Rails ActiveRecord Shovel(<<)运算符

所以我的应用程序中的代码附加了与“<<”相关的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函数中被激活,这会提示我询问:

怎么<<运算符在activerecord中工作,我在哪里可以阅读更多信息? 谢谢

解决方法

当您使用铲运算符(<<<<<<<<<<<<<所以,当你这样做时:
self.comments << @new_comment

@new_comment被添加到comments集合中,并立即触发更新sql而不等待父对象上的保存或更新调用,除非父对象是新记录.

this documentation

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.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...