accepts_nested_attributes_for:models,allow_destroy:true不起作用

时间:2015-06-13 18:57:21

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

我的参数是这样的:

"job" => {"title"=>"Marketing Head", "job_role_id"=>"13", 
  "challenge_assignments_attributes"=>{
    "0"=>{"_destroy"=>"true", "challenge_id"=>"13", "id"=>"12"}, 
    "1"=>{"_destroy"=>"true", "challenge_id"=>"13", "id"=>"13"}
  }
 }

我有工作.rb
    accepts_nested_attributes_for :challenge_assignments, reject_if: :all_blank, allow_destroy: true

在job_controller.rb中我允许这些     challenge_assignments_attributes: [:id, :challenge_id, :_destroy]

然而,在保存对象时不会被破坏。我有另一个模型以相同的方式设置,_destroy键适用于它。两者的配置相同,但其中一个不起作用。

还有其他条件,其中allow_destroy不起作用,因为我试图查看源代码也无济于事。

现在我已经做了一个猴子补丁来自己移除物体。但这显然不是最佳方式。

challenge_assignments = job_params['challenge_assignments_attributes']
flag = false
challenge_assignments.each do |k,v|
     if ['t', '1', 'true'].include? v['_destroy']
       ChallengeAssignment.find(v['id']).destroy
       flag = true
     end
end
flag ? jp = job_params.except!("challenge_assignments_attributes") : jp = job_params

Job.rb

class Job < ActiveRecord::Base
  has_many :challenge_assignments, dependent: :destroy
  has_many :jobs, through: :challenge_assignments
  has_many :challenge_assignments, dependent: :destroy
  has_many :challenges, through: :challenge_assignments

  accepts_nested_attributes_for :challenge_assignments, reject_if: :all_blank, allow_destroy: true


end

1 个答案:

答案 0 :(得分:0)

在发布我的模型代码之后,我注意到我从连接的另一端写了重复的has_many,我错误地复制了它。感谢那位引起我注意的评论者。