[英]Why doesn't accepts_nested_attributes_for allow_destroy not work?
[英]accepts_nested_attributes_for allow_destroy doesn't work with scoped validation
我想弄清楚为什么accepts_nested_attributes_for
接收到这样的哈希后不会破坏记录:
{project_parcels_attributes"=>[{"parcel_id"=>"680060", "_destroy"=>"1"}, {"parcel_id"=>"680088"}]}
使用的上下文如下。 有一个项目模型:
class Project < ActiveRecord::Base
has_many :project_parcels
accepts_nested_attributes_for :project_parcels, allow_destroy: true
end
class ProjectParcels < ActiveRecord::Base
belongs_to :project
belongs_to :parcel
validates :parcel_id, uniqueness: {scope: :project_id}
end
然后我从这样的形式调用它:
@project.update_attributes({"project_parcels_attributes"=>[{"parcel_id"=>"680060", "_destroy"=>"1"}, {"parcel_id"=>"680088"}]})
但是,它不起作用。 验证使记录不再被破坏。 但是,当我删除验证时,记录会被添加多次。
您应该通过hidden_field标签添加子对象的ID
<%= f.hidden_field :id %>
然后使用id更新:
{project_parcels_attributes"=>[{id: an_id, "parcel_id"=>"680060", "_destroy"=>"1"}, {id: an_id, "parcel_id"=>"680088"}]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.