简体   繁体   中英

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

Are you maybe using delete instead of destroy ? Using destroy will cause dependents to be removed while delete does not. see this

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

Try this:

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

Use destroy_all instead of delete_all if you have *_destroy callbacks in the ThreadParticipation model. The delete_all call is faster than destroy_all as it performs deletion of multiple rows in one DB call and does not have the overhead of invoking the *_destroy callbacks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM