开发者

Rails accepts_nested_attributes_for _destroy doesnt work unless associations are already loaded

Rails 3.0.5 doesn't seem to destroy children of a parent object using accepts_nested_attributes_for unless the children are loaded. Does anyone know if this is by design? It seems a b开发者_StackOverflow中文版it odd to me. Here's the setup.

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


Foo#bars is a has_many so it will be expecting more than 1 thing, which means an Array. Try passing an Array of Hash like so:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜