除非已经加载了关联,否则Rails accepts_nested_attributes_for _destroy不起作用

时间:2011-04-06 15:44:27

标签: ruby-on-rails ruby nested-attributes

除非子项被加载,否则Rails 3.0.5似乎不会使用accepts_nested_attributes_for来销毁父对象的子对象。有谁知道这是否是设计的?这对我来说似乎有点奇怪。这是设置。

class Foo < AR
  has_many :bars
  accepts_nested_attributes_for :bars, :allow_destroy => true
end

class Bar < AR
  belongs_to :foo
end

# create a Foo with 5 bars (ie. Foo.create :bars_attributes => ... )
# then fetch a foo, without its bars

f = Foo.find(1)
f.update_attributes("bars_attributes" => {"id" => "1", "_destroy" => "1"})
Foo.find(1).bars.length   # => 5

f = Foo.find(1, :include => :bars)
f.update_attributes("bars_attributes" => {"id" => "1", "_destroy" => "1"})
Foo.find(1).bars.length   # => 4

1 个答案:

答案 0 :(得分:1)

Foo#bars是一个has_many所以它会超过一件事,这意味着Array。尝试传递Array Hash,如此:

f = Foo.find(1, :include => :bars)
f.update_attributes("bars_attributes" => [{"id" => "1", "_destroy" => "1"})]
相关问题