Search code examples
ruby-on-railsruby-on-rails-3activemodel

Rails - Help understanding how to use :dependent => :destroy


I have the following models:

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

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.

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

Thoughts? Thanks


Solution

  • 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