0
votes

I have a Resume Model that has_many :skills, and my skills model that belongs_to :resume.

I am nesting the skills form inside the resume form and it's creating the record and relationship perfectly. But when I try to destroy the resume, the associated Skill is not being destroyed along with it.

Here are my models:

# Resume.rb

class Resume < ActiveRecord::Base
  has_many :skills

  belongs_to :user

  accepts_nested_attributes_for :skills, allow_destroy: true
end 


# Skill.rb

class Skill < ActiveRecord::Base
  belongs_to :resume
end

Here's the strong params in the resume_controller.rb

def resume_params
  params.require(:resume).permit(:user_id, :title, :summary, :job_title, skills_attributes [:skill_name, :_destroy])
end

As far as I can tell I am passing the _destroy key properly. I noticed some people had _destroy checkboxes in the form. I want the Skills to be deleted when I Destroy the entire resume. Thanks!

2

2 Answers

2
votes

All you have specified is that you can destroy skills on a resume like with the checkboxes you mention seeing in some examples. If you want it to destroy all skills associated when a resume is destroyed you have adjust your has_many declaration.

has_many :skills, dependent: :destroy
2
votes

Add :dependent => :destroy in your Resume model like below:

class Resume < ActiveRecord::Base
  has_many :skills, :dependent => :destroy

  belongs_to :user

  accepts_nested_attributes_for :skills, allow_destroy: true
end 

:dependent Controls what happens to the associated objects when their owner is destroyed:

  • :destroy causes all the associated objects to also be destroyed

  • :delete_all causes all the associated objects to be deleted directly from the database (so callbacks will not execute)

  • :nullify causes the foreign keys to be set to NULL. Callbacks are not executed.

  • :restrict_with_exception causes an exception to be raised if there are any associated records

  • :restrict_with_error causes an error to be added to the owner if there are any associated objects