Rails - 帮助理解如何使用 :dependent =>:破坏 [英] Rails - Help understanding how to use :dependent => :destroy

查看:34
本文介绍了Rails - 帮助理解如何使用 :dependent =>:破坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

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

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

So that's working nicely, problem is this. When a user leaves or is removed from a project, I need all their ThreadParticipation's for that project deleted.

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

Example, so if user(15), leaves project(3) by deleting the permission (user_id =>15, project_id => 3), I need rails to automatically then delete all related ThreadParticipation records (where ThreadParticipation through thread, belongs to project_id 3, and ThreadParticipation.user_id = 15.

我已经试过了,但它没有做任何事情:

I've tried this, but it's not doing anything:

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

想法?谢谢

推荐答案

Permission 模型中,这样做:

In the Permission Model, do this:

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

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

This is considering you have relationships defined in the models

这篇关于Rails - 帮助理解如何使用 :dependent =>:破坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆