除去代替销毁对象时assosiation:allow_destroy =>真
-
18-09-2019 - |
题
当在ActiveRecord的使用新accepts_nested_attributes_for
,有可能使用的选项:allow_destroy => true
。当这个选项被设置时,含有嵌套任何散列像{"_delete"=>"1", "id"=>"..."}
传递给update_attributes
将删除嵌套的对象属性。
设置简单:
class Forum < ActiveRecord::Base
has_many :users
accepts_nested_attributes_for :users, :allow_destroy => true
end
class User < ActiveRecord::Base
belongs_to :forum
end
Forum.first.update_attributes("users_attributes"=>{"0"=>{"_delete"=>"1", "id"=>"42"}})
问:如何做我 - 而不是删除嵌套对象时"_delete" => "1"
- 只是删除关联? (即在上述情况下所设定的用户为nil的forum_id)
奖金的问题::如果我也想删除的关联时,更改嵌套对象的属性是什么? (例如像设置的状态或时间戳记)
解决方案
除了要求用户的使用"_delete" => '1'
你被删除,不能随便使用nested_attributes更新:
Forum.first.update_attributes("users_attributes"=> {
"0" => {
"id" => "42",
"forum_id" => "",
"state" => 'removed'
}
})
不隶属于 StackOverflow