2012-08-22 43 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修改时间更改。