Rails: How to use dependent: :destroy in rails?
Ruby on-RailsRubyRuby on-Rails-3Ruby on-Rails-4Ruby on-Rails-3.2Ruby on-Rails Problem Overview
I have 2 models as describes below.
class EmpGroup < ActiveRecord::Base
belongs_to :user
has_many :emp_group_members, dependent: :destroy
end
and
class EmpGroupMember < ActiveRecord::Base
belongs_to :emp_group
belongs_to :user
end
now the problem is whenever I tried to destroy a group then I received a error as below.
PG::ForeignKeyViolation: ERROR: update or delete on table "emp_groups" violates foreign key constraint "fk_rails_bd68440021" on table "emp_group_members"
DETAIL: Key (id)=(1) is still referenced from table "emp_group_members".
What I'm missing?
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
Add cascading delete to your EmpGroup
model:
class EmpGroup < ActiveRecord::Base
has_many :emp_group_members, dependent: :delete_all
end
Or
Are you calling delete
method? you should call destroy
instead.
Use .destroy
Solution 2 - Ruby on-Rails
:dependent is one of the options available in belongs_to association
If you set the :dependent option to:
:destroy, when the object is destroyed, destroy will be called on its associated objects.
:delete, when the object is destroyed, all its associated objects will be deleted directly from the database without calling their destroy method.
Additionally, objects will be destroyed if they're associated with dependent: :destroy, and deleted if they're associated with dependent:
:delete_all.
in has_many associations:
: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)
you can try
emp_member_1= @emp_group.emp_group_members.first
##delete associated record
@emp_group.emp_group_members.delete(emp_member_1)
Solution 3 - Ruby on-Rails
New syntax:
class EmpGroup < ActiveRecord::Base
has_many :emp_group_members, dependent: :destroy
end
Solution 4 - Ruby on-Rails
When you delete a group, are you using delete or destroy. - I've had this error before, and it was because I had a typo and was using .delete instead of .destroy
Solution 5 - Ruby on-Rails
Insert relation like this
has_many :children, :dependent => :destroy
To learn more about destroy and delete, go to this link https://medium.com/@wkhearn/delete-vs-destroy-does-it-even-matter-8cb4db6aa660