Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

ruby - Rails: How to use dependent: :destroy in rails?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...