1

假設我們有一個用戶。在Rails中,如何將這兩個不同的has_manys合併爲一個?

用戶的has_many文件通過賬號是這樣的...

class User < ActiveRecord::Base 
    belongs_to :account 
    has_many :documents, :through => :account, :order => "created_at DESC" 
end 

class Account < ActiveRecord::Base 
    has_one :owner, :class_name => "User", :dependent => :destroy 
    has_many :documents, :dependent => :destroy 
end 

class Document < ActiveRecord::Base 
    belongs_to :account 
end 

尼斯和簡單,這是它得到棘手......

用戶也可對文檔進行協作,這通過合作者加入表...

class Collaborator < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :documnet 
end 

class Document < ActiveRecord::Base 
    has_many :collaborators, :dependent => :destroy 
    has_many :users, :through => :collaborators 
    accepts_nested_attributes_for :collaborators, :allow_destroy => true 
end 

這是我不確定的最終用戶位。我想補充另一個有很多的文件,當你調用user.documents它融合通過他們的帳戶,他們正在合作開發的那些兩個文件...

class User < ActiveRecord::Base 
    belongs_to :account 
    has_many :documents, :through => :account, :order => "created_at DESC" 

    #documents need to do both has manys… 
    has_many :collaborators, :dependent => :destroy 
    has_many :documents, :through => :collaborators 
end 

謝謝,這是一個有點長,但我能想到的一個整潔的解決方案。任何幫助將非常感激。

回答

3

您可以創建將要求在表上documentsaccountscollaborators找到與用戶的文件的方法:

class User < ActiveRecord::Base 

    #... 

    def documents 
    Document.includes(:account, :collaborators).where('collaborators.user_id = ? OR documents.account_id = ?', self.id, self.account.id) 
    end 

end 

我沒有測試這個要求,但我希望你得到的理念。如果錯誤,請糾正。

對於2 has_many documents, :through...,你可以刪除它們,如果你不再需要它們;否則,你必須給他們不同的名字(和上面的方法不同)。

+0

謝謝!我修改了一下,使其工作,添加我的更改。乾杯。 – Smickie

相關問題