2012-08-22 44 views
0

我有以下型號:Mongoid,複雜查詢,類似的has_many東西:通過

class Company 
    # ... 
    has_many :invoices 
end 

class Invoice 
    # ... 
    belongs_to :company 
    has_many :items 

    field :type, String 

    scope :expense, where(type: 'expense') 
    scope :income, where(type: 'income') 
end 

class Item 
    # ... 
    belongs_to :invoice 
end 

的問題是如何獲取所有income項目對於給定的公司?

類似的東西來company.items.expense

回答

-1

使用嵌入關係將不會有任何區別。調用company.items.expense仍然會返回一個錯誤,因爲company.items返回一個數組。

嘗試這樣:

class Company 
    #... 
    def expenses 
    self.invoices.where(type: 'expense') 
    end 

    def incomes 
    self.invoices.where(type: 'income') 
    end 
end 

然後就可以調用company.expenses和​​。

根據您的使用情況,您可能會發現將Item嵌入Invoice或將其作爲單獨收藏夾更好。另外,由於您正在處理髮票,因此請記住要小心回調並在必要時進行級聯,因此如果Item被更改,Invoice修改時間更改。