加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 04:29:17 所属栏目:百科 来源:网络整理
导读:所以我的应用程序中的代码附加了与“”相关的has_many关系像这样的运算符: class BlogPost ActiveRecord::Base has_many :comments def add_comment(content) @new_comment = Comment.create(content) self.comments @new_comment endend 它似乎工作.我从来
所以我的应用程序中的代码附加了与“<<”相关的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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读