2012-05-04 84 views
1

我正在開發一個Rails應用程序,供用戶創建項目。有兩種類型的用戶AdminsCollaborators。管理員和協作者has_many :accounts, through: :account_users,其中account_users是連接表。當管理員刪除他們的帳戶時,我也想刪除他們創建的帳戶和它的項目,但我無法讓這個工作。我的模型目前看起來是這樣的:通過has_many關係刪除對象:dependent =>:destroy Rails 3.2

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 

當管理員用戶刪除它的賬號,僅在連接表和用戶表中的行被刪除,他們的項目不會被刪除。

注意,我使用設計來處理驗證。

我該如何解決這個問題?

+0

您有混合哈希語法:'通過::account_users,:dependent =>:destroy' ...最好選擇其中一個或另一個 – tybro0103

回答

4

我沒有看到一個項目的聯繫,所以我想你可以做它的兩種方法之一:

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 
+0

我與ActiveRecord關係有同樣的問題,所以我不得不使用'self.other.destroy_all'銷燬集合。 – rxgx

+0

謝謝,但我並沒有完全明白它的作用。問題不在於銷燬帳戶項目,而在於管理員帳戶(公司可能是更好的帳戶名稱)。我嘗試了你的第一種方法:'after_save:destroy_accounts'和'def destroy_accounts self.accounts.delete_all if self.destroyed? end'。但它不會銷燬關聯的帳戶。 – Anders

+0

我想我得到它與你的第一個建議非常類似的解決方案,但我用before_destroy,而不是after_save,並在輔助方法中的一些小的變化:'def destroy_accounts accounts = self.accounts.where(「account_owner = '#{self.id}'「) accounts.destroy_all end'。我需要做一些測試,但我認爲它會起作用。我的解決方案有什麼缺點嗎? 結束 – Anders

相關問題