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

点点圈 提交于 2019-12-29 09:09:10

问题


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


回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/4998239/rails-help-understanding-how-to-use-dependent-destroy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!