Carlos Martinez
Carlos Martinez

Reputation: 4510

How do you delete children records with multiple belongs_to?

My models look like this:

class Project < ActiveRecord::Base
 has_many :entries
end

class User < ActiveRecord::Base
 has_many :entries
end

class Entry < ActiveRecord::Base
 belongs_to :user
 belongs_to :project
end

I want to delete every Entry that depends on a Project when it gets deleted. I'm using Postgres with UUID's as their ID's. I've tried this:

class Project < ActiveRecord::Base
 has_many :entries, dependent: :destroy
end

And this:

class Project < ActiveRecord::Base
 has_many :entries

 before_destroy { |project| Entry.destroy_all "project_id = #{project.id}" }
end

But when the project gets deleted, the entries are still there. I think the reason would be that they still have another parent object.

I also tried to delete them from my controller:

def destroy
   @project = current_company.projects.find(params[:id])
   @project.time_entries.delete_all
   ...
end

What's the problem, am I missing something?

Upvotes: 0

Views: 864

Answers (1)

Ryan K
Ryan K

Reputation: 4053

The line has_many :entries, dependent: :destroy should work. However, it all depends on how you remove the project. If you say

@project.delete

then it will never work, as delete skips the callbacks, which would remove all the entries. Instead, try using something like

@project.destroy

then it should work as destroy does call callbacks. BTW, the same rules holds true for the delete_all and destroy_all variants.

Upvotes: 1

Related Questions