accepts_nested_attributes_for allow_destroy不适用于范围验证

时间:2014-10-13 21:21:42

标签: ruby-on-rails rails-activerecord nested-forms

我想弄清楚为什么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"}]})

然而,它并没有奏效。验证会阻止记录被销毁。但是当我删除验证时,记录会多次添加。

1 个答案:

答案 0 :(得分:1)

你应该用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"}]}
相关问题