更新嵌套属性集合后是否有必要调用 ActiveRecord::Base.reload ?
我发现(在脚本/控制台中闲逛)如果我将新项目添加到关联的集合中,我不必调用 foo.reload 来查看结果更改:
foo.bars
=> []
foo.bars_attributes = [{ :person_id => '288', :task_id => '1237' }]
=> [{ :person_id=>"288", :task_id=>"1237" }]
foo.save
=> true
foo.bars
=> [#<Bar id: 6, person_id: 288, task_id => 1237>]
太棒了。但是,当我从集合中删除项目时,我必须在更改(调用保存后在数据库中可见)反映在我的集合中之前调用 foo.reload:
foo.bars_attributes = [{ :id => '6', :_delete => '1' }]
= [{ :_delete=>"1", :id=>"6" }]
foo.save
=> true
foo.bars
=> [#<Bar id: 6, person_id: 288, task_id => 1237>]
foo.reload
foo.bars
=> []
这是正常的,还是我在关联中做了一些稍微错误的事情更新?
I am finding (noodling around in script/console) that if I add a new item to the associated collection, I don't have to call foo.reload to see the resulting change:
foo.bars
=> []
foo.bars_attributes = [{ :person_id => '288', :task_id => '1237' }]
=> [{ :person_id=>"288", :task_id=>"1237" }]
foo.save
=> true
foo.bars
=> [#<Bar id: 6, person_id: 288, task_id => 1237>]
Terrific. But when I remove an item from the collection, I do have to call foo.reload before the change (visible in DB after call to save) is reflected in my collection:
foo.bars_attributes = [{ :id => '6', :_delete => '1' }]
= [{ :_delete=>"1", :id=>"6" }]
foo.save
=> true
foo.bars
=> [#<Bar id: 6, person_id: 288, task_id => 1237>]
foo.reload
foo.bars
=> []
Is this normal, or am I doing something slightly wrong in the association update?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在 Rails 3.0 中看到了同样的事情(在您撰写本文时尚未发布)。它因需要最少数量的关联的验证而造成严重破坏。即使更新删除了所有子属性,父实例也会说它是有效的。
我设计了一种解决方法,通过使用以下方法在我的
Parent
模型中包含一个模块,并将其替换为控制器的update
方法中的update_attributes()
:这绝不是一个完美的解决方案,并且尚未在更深层的嵌套关联上进行测试。
快一年了,让总比不让好!
I'm seeing the same thing in rails 3.0 (no yet released at the time of your writing). It was reaping havoc with a validation that required a minimum number of associations. The parent instance would say it was valid, even after the update had removed all the child attributes.
I devised a workaround by including a module in my
Parent
model with the following method, and substituting that forupdate_attributes()
in the controller'supdate
method:This is by no means a perfect solution, and it's untested on more deeply nested associations.
Better let than never, almost a year to the day!