我有以下型号:
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通过thread,属于project_id 3,ThreadParticipation.user_id = 15.
我试过这个,但它没有做任何事情:
has_many :thread_participations, :foreign_key => :user_id, :dependent => :destroy
思考?感谢
答案 0 :(得分:2)
您是否可以使用delete
代替destroy
?使用destroy
会导致依赖项被删除,delete
则不会。 see this
答案 1 :(得分:1)
在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
考虑到您在模型中定义了关系
答案 2 :(得分:1)
试试这个:
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
如果destroy_all
型号中有delete_all
次回调,请使用*_destroy
代替ThreadParticipation
。 delete_all
调用比destroy_all
快,因为它在一次数据库调用中删除了多行,并且没有调用*_destroy
回调的开销。