2

我有以下型号:

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通过线程,属于project_id 3,并且 ThreadParticipation.user_id = 15。

我试过这个,但它没有做任何事情:

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

想法?谢谢

4

3 回答 3

2

你可能使用delete而不是destroy?使用destroy会导致家属被移除,而delete不会。看到这个

于 2011-02-15T01:34:19.830 回答
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

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

于 2011-02-14T23:06:37.997 回答
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而不是。该调用比在一个 DB 调用中执行删除多行更快,并且没有调用回调的开销。delete_all*_destroyThreadParticipationdelete_alldestroy_all*_destroy

于 2011-02-15T00:10:35.067 回答