Rails Accepts_nested_attributes_for _destroy 不起作用,除非关联已经加载
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
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 bit 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Foo#bars
是一个has_many
,因此它会期望不止 1 个东西,这意味着一个Array
。尝试传递Hash
的Array
,如下所示:Foo#bars
is ahas_many
so it will be expecting more than 1 thing, which means anArray
. Try passing anArray
ofHash
like so: