在更新期间销毁关联模型时重复记录

时间:2014-11-15 19:05:44

标签: ruby-on-rails ruby-on-rails-4

日冰, 我在ROR 4.1.6.rc1上 我有一个如下所述的模型

class MainSlot < ActiveRecord::Base
  ... 
  has_many :citizenship_requirements, dependent: :destroy
  accepts_nested_attributes_for :citizenship_requirements, :allow_destroy => true, reject_if: lambda { |attribute| attribute['citizenship_id'] == "0" }
  ...
end

尝试根据复选框更新citizenship_requirements关联,以便删除未选中的关联模型

MainSlotsController:

def edit
  @company = Company.find(@company_id)
  @main_slot = MainSlot.find(params[:id])

  respond_to do |format|
    format.js
  end
end

def update
  binding.pry
  main_slot = MainSlot.find(params[:id])
  if main_slot.update_attributes(main_slot_params)
    flash[:success] = "Job is successfully updated!"
    redirect_to main_slots_path
  else
    flash[:success] = "There was an error updating the job. Please try again."
    redirect_to main_slots_path
  end
end

private
  def main_slot_params
    params.require(:main_slot).permit(
      :id, 
      ..., 
      company_job_title_attributes: [:id, :job_title_name, :job_function_id, :company_id], 
      citizenship_requirements_attributes: [:id, :citizenship_id, :_destroy, :cr_id],
      ... )
  end

在binding.pry所在的行,我的参数就是这样(cr_id是主键)

"main_slot"=>
{
  ...
  "citizenship_requirements_attributes"=>
   [{"citizenship_id"=>"1", "cr_id"=>"6033", "_destroy"=>"true"},
    {"citizenship_id"=>"2", "cr_id"=>"6034", "_destroy"=>"true"},
    {"citizenship_id"=>"3", "cr_id"=>"6035", "_destroy"=>"true"},
    {"citizenship_id"=>"4", "cr_id"=>"6036", "_destroy"=>"true"}],
...
}

然而,在更新时,没有任何事情发生。该记录仍然保持相同的cr_id等。

我应该如何在更新时删除嵌套模型?

此外,对于这样的参数

"main_slot"=>
{
  ...
  "citizenship_requirements_attributes"=>
   [{"citizenship_id"=>"1", "cr_id"=>"6033", "_destroy"=>"false"},
    {"citizenship_id"=>"2", "cr_id"=>"6034", "_destroy"=>"false"},
    {"citizenship_id"=>"3", "cr_id"=>"6035", "_destroy"=>"true"},
    {"citizenship_id"=>"4", "cr_id"=>"6036", "_destroy"=>"true"}],
...
}

我收到关键'PRIMARY'的错误“重复输入'6033'”。 Rails文档说“如果哈希包含与已关联记录匹配的id密钥,则匹配记录将被修改:”用于更新此链接中的嵌套模型:“http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

不确定我做错了什么:(

提前致谢!

1 个答案:

答案 0 :(得分:0)

感谢@blelump,你是对的。当我的params被制作出来时它起作用了:

"main_slot"=>
{
  ...
  "citizenship_requirements_attributes"=>
   [{"citizenship_id"=>"1", "id"=>"6033", "_destroy"=>"false"},
    {"citizenship_id"=>"2", "id"=>"6034", "_destroy"=>"false"},
    {"citizenship_id"=>"3", "id"=>"6035", "_destroy"=>"true"},
    {"citizenship_id"=>"4", "id"=>"6036", "_destroy"=>"true"}],
  ...
}

它只是像你所说的那样寻找'id'和'id'。奖励