kartikluke
kartikluke

Reputation: 2405

accepts_nested_attributes_for :models, allow_destroy: true not working

My params are like so:

"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"}
  }
 }

I have in my job.rb
accepts_nested_attributes_for :challenge_assignments, reject_if: :all_blank, allow_destroy: true

And in job_controller.rb I permit these challenge_assignments_attributes: [:id, :challenge_id, :_destroy]

Yet on saving the objects don't get destroyed. I have another model set up in the same way and the _destroy key works for it. The configuration for both is the same yet one works and the other doesn't.

Are there any other conditions under which allow_destroy doesn't work cause I've tried to look at the source code as well to no avail.

For now I've made a monkey patch to remove the objects myself. But this clearly isn't the best way to go about it.

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

Upvotes: 0

Views: 416

Answers (1)

kartikluke
kartikluke

Reputation: 2405

After posting my model code I noticed I had written duplicate has_many from the other side of the join that I'd copied over by mistake. Thanks to the commenter that brought my attention to it.

Upvotes: 1

Related Questions