Rails – 帮助理解如何使用:dependent =>:destroy

我有以下型号:

User (id) Project (id) Permission (project_id, user_id) Thread (project_id) ThreadParticipation (thread_id, user_id) 

所以这很好用,问题是这个。 当用户离开或从项目中删除时,我需要删除该项目的所有ThreadParticipation。

例如,如果用户(15)通过删除权限(user_id => 15,project_id => 3)离开项目(3),我需要rails自动然后删除所有相关的ThreadParticipation记录(其中ThreadParticipation通过线程属于project_id) 3,和ThreadParticipation.user_id = 15。

我试过这个,但它没有做任何事情:

 has_many :thread_participations, :foreign_key => :user_id, :dependent => :destroy 

思考? 谢谢

Permission模型中,执行以下操作:

 before_destroy :delete_thread_participation private def delete_thread_participation if self.threadparticipation self.threadparticipation.delete_all "project_id ="+self.project_id+"and user_id="+self.user_id end end 

这是考虑到您在模型中定义了关系

你可能使用delete而不是destroy ? 使用destroy将导致delete依赖项,而delete则不会。 看到这个

试试这个:

 class Project has_many :threads has_many :thread_participations, :through => :threads end class Permission belongs_to :project after_destroy :destroy_thread_participations def destroy_thread_participations ThreadParticipation.delete_all( :id => project.thread_participations.find_all_by_user_id(user_id) ) end end 

如果在ThreadParticipation模型中有*_destroy回调,请使用destroy_all而不是delete_alldelete_all调用比destroy_all快,因为它在一次DB调用中执行多行删除,并且没有调用*_destroy回调的开销。