【问题标题】:Delete object in a has_many through relationship with :dependent => :destroy Rails 3.2通过与 :dependent => :destroy Rails 3.2 的关系删除 has_many 中的对象
【发布时间】:2012-05-04 18:05:51
【问题描述】:

我正在开发一个 Rails 应用程序,用户可以在其中创建项目。有两种类型的用户AdminsCollaborators。 Admins 和 Collaborators has_many :accounts, through: :account_users,其中 account_users 是一个连接表。当管理员删除他们的帐户时,我也想删除他们创建的帐户和它的项目,但我无法让它工作。我的模型目前看起来像这样:

class Collaborator < User
  [...]  
  has_many :account_users
  has_many :accounts, through: :account_users
  [...]
end

class Admin < User
  has_many :account_users
  has_many :accounts, through: :account_users, :dependent => :destroy
  [...]
end 

class Account < ActiveRecord::Base
  [...]
  belongs_to :admin
  has_many :account_users
  has_many :collaborators, through: :account_users
  [...]
end


class AccountUser < ActiveRecord::Base
  belongs_to :admin
  belongs_to :account
  belongs_to :collaborator
end

当管理员用户删除其帐户时,仅删除联接表和用户表中的行,不会删除他们的项目。

注意,我使用 devise 来处理身份验证。

我该如何解决这个问题?

【问题讨论】:

  • 你有一个混合哈希语法:through: :account_users, :dependent =&gt; :destroy ...最好选择一个或另一个

标签: ruby-on-rails ruby database activerecord


【解决方案1】:

我没有看到项目关联,所以我认为您可以通过以下两种方式之一进行:

class Account < ActiveRecord::Base
   after_save :destroy_projects

   private
   def destroy_projects
      self.projects.delete_all if self.destroyed?
   end
end

class Account < ActiveRecord::Base
  [...]
  belongs_to :admin
  has_many :account_users
  has_many :collaborators, through: :account_users
  has_many :projects, :dependent => :destroy
  [...]
end

【讨论】:

  • 我在 ActiveRecord 关系中遇到了同样的问题,所以我不得不使用 self.other.destroy_all 销毁集合。
  • 谢谢,但我并没有完全让它工作。问题不在于销毁帐户项目,而是销毁管理员帐户(公司可能是帐户的更好名称)。我尝试了这样的第一种方法:after_save :destroy_accountsdef destroy_accounts self.accounts.delete_all if self.destroyed? end。但它不会破坏关联的帐户。
  • 我想我可以使用与您的第一个建议非常相似的解决方案,但我使用了 before_destroy 而不是 after_save,并且对辅助方法进行了一些小的更改:def destroy_accounts accounts = self.accounts.where("account_owner = '#{self.id}'") accounts.destroy_all end。我需要做一些测试,但我认为它会起作用。我的解决方案有什么缺点吗?结束
猜你喜欢
  • 2015-11-23
  • 2011-02-17
  • 2012-07-09
  • 1970-01-01
  • 1970-01-01
  • 2011-04-14
  • 1970-01-01
  • 2013-01-10
  • 1970-01-01
相关资源
最近更新 更多