【问题标题】:ActiveRecord autosave:false doesn't appear to workActiveRecord 自动保存:false 似乎不起作用
【发布时间】:2011-06-20 20:56:23
【问题描述】:

根据docs,在关联上设置:autosave => false 不应在保存父级时保存这些关联。这似乎对我不起作用。我刚刚创建了一个香草 Rails 3.0.8 应用程序,这就是我得到的:

class Foo < ActiveRecord::Base
  has_many :bars, :autosave => false
  accepts_nested_attributes_for :bars
end

class Bar < ActiveRecord::Base
  belongs_to :foo
end

f = Foo.new :name => 'blah', :bars_attributes => [{:name => 'lah'},{:name => 'lkjd'}]
f.save
f.bars
 => [#<Bar id: 1, name: "lah", foo_id: 1, created_at: "2011-06-20 20:51:02", updated_at: "2011-06-20 20:51:02">, #<Bar id: 2, name: "lkjd", foo_id: 1, created_at: "2011-06-20 20:51:02", updated_at: "2011-06-20 20:51:02">]

什么?为什么要保存bars

我觉得我正在服用疯狂的药丸!我错过了什么?

更新:似乎accepts_nested_attributes_for 会自动保存子项,即使它们不是使用嵌套属性功能构建的。它认为这是一个错误。

【问题讨论】:

  • 运行给定代码后f.bars.first.new_record? 的输出是什么?
  • 我在上面输出了f.bars。很明显,new_record? 将返回 false,因为它已使用 ID 持久化。同样,这只发生在使用 accepts_nested_attributes_for

标签: ruby-on-rails activerecord autosave


【解决方案1】:

这不是错误,而是有意为之。见http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

点击方法accepts_nested_attributes_for 上的“Source: show”也证明了这一点。

请注意, :autosave 选项会自动启用 accept_nested_attributes_for 用于的关联。

【讨论】:

    【解决方案2】:

    添加到 Innerpeacer 响应中,如果您使用 Accepts_nested_attributes_for,将 autosave 属性设置为 false 是没有意义的。 使用accepts_nested_attributes_for的原因之一是同时保存children和parent。

    你可以做的是:

    f = Foo.new :name => 'blah'
    f.save
    f.bars_attributes = [{:name => 'lah'},{:name => 'lkjd'}]
    

    f = Foo.new :name => 'blah'
    f.save
    f.bars = [Bars.new({:name => 'lah'}), Bars.new({:name => 'lkjd'})]
    

    【讨论】:

      猜你喜欢
      • 2011-10-19
      • 1970-01-01
      • 2018-04-17
      • 1970-01-01
      • 2013-01-31
      • 2011-05-22
      • 2011-11-18
      • 2013-10-15
      • 1970-01-01
      相关资源
      最近更新 更多