微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/ruby/269090.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐