1

根据目前的 Rails 文档,关于现有对象<<的 has_many 关系上的运算符:

collection<<(object, …)

Adds one or more objects to the collection by setting their foreign keys
to the collection’s primary key. 

(这是有趣的一点)

Note that this operation instantly fires update sql without waiting for 
the save or update call on the parent object.

我没有意识到会发生这种情况,我很惊讶;我本可以发誓过去并非如此,尽管我承认我可能是错的。

在任何一种情况下,我都无法找到任何关于此的其他文档,但是我想知道是否有办法阻止此更新?

我的情况很简单,我只有一个存在于数据库中的对象,正在为“编辑”页面做准备。我在页面呈现之前附加一个或多个相关对象。C'est吹捧。

更新:如果您使用运算符直接从数组设置 has_many 关系,显然也会发生相同的更新场景=

4

1 回答 1

1

使用集合的build方法。这不会像其他人那样立即触发 SQL 语句。

foo.bars.build(attributes)
foo.save

在这里可以找到很多好的信息:http: //api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

注意:此方法假定您可以灵活地通过 build 方法创建对象,而不是使用Bar.new.

于 2012-11-01T17:04:18.777 回答