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
1.0k views
in Technique[技术] by (71.8m points)

ruby on rails - dependent => destroy on a "has_many through" association

Apparently dependent => destroy is ignored when also using the :through option.

So I have this...

class Comment < ActiveRecord::Base
  has_many :comment_users, :dependent => :destroy
  has_many :users, :through => :comment_users
  ...
end

...but deleting a Comment does not result in the associated comment_user records getting deleted.

What's the recommended approach, then, for cascade deletes when using :through?

Thanks

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Apparently :dependent is not ignored!

The real issue was that I was calling Comment.delete(id) which goes straight to the db, whereas I now use Comment.destroy(id) which loads the Comment object and calls destroy() on it. This picks up the :dependent => :destroy and all is well.


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

...