Rails Accepts_nested_attributes_for _destroy 不起作用,除非关联已经加载

发布于 2024-10-30 22:44:43 字数 691 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

听不够的曲调 2024-11-06 22:44:43

Foo#bars 是一个 has_many,因此它会期望不止 1 个东西,这意味着一个 Array。尝试传递 HashArray,如下所示:

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

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"})]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文