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

标签 ruby-on-rails ruby ruby-on-rails-4 activerecord ruby-on-rails-5

所以我的应用程序中有代码附加到与“<<”运算符的 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,而无需等待对父对象的保存或更新调用,除非父对象是新记录。

来自 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.

关于ruby-on-rails - Rails ActiveRecord Shovel (<<) 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32941230/

相关文章:

javascript - react 未定义

ruby-on-rails - Rails : attributes not being saved even though I called @user. 保存

ruby-on-rails - Ruby on Rails 路由 : Multiple namespaces and multiple domains: best practice?

ruby-on-rails - 在 Thinking Sphinx 中使用 Delta 索引进行关联

ruby-on-rails - 如何测试特定 Assets (JS、CSS)在布局中是否可用?

ruby-on-rails - ActiveRecord 更新不更新我的专栏

ruby-on-rails - _mask 和 Rails

ruby-on-rails - Rails 3 中的 fields_for 问题

ruby - 带有 dict 元素的 Plist XPath 查询

ruby-on-rails - 如何检查字符串是否包含特定字符,以及它是否仅替换该位?