当:allow_destroy => true时,删除关联而不是销毁对象

3
在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"时,我该如何删除嵌套对象并仅删除关联?(即在上述情况下将用户的forum_id设置为nil)

附加问题: 如果我想在删除关联时同时更改嵌套对象上的属性怎么办?(例如像设置状态或时间戳)

1个回答

3

你可以尝试使用嵌套属性更新用户信息,而不是使用"_delete" => '1' 删除用户:

Forum.first.update_attributes("users_attributes"=> { 
  "0" => {
    "id" => "42",
    "forum_id" => "",
    "state" => 'removed'
  }
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接