2012-08-22 5 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이 배열을 반환하기 때문에 company.items.expense을 호출해도 오류가 반환됩니다. 이 같은

시도 뭔가 :

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

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

는 그런 다음 company.expensescompany.incomes를 호출 할 수 있습니다.

용도에 따라 ItemInvoice 안에 삽입하거나 별도의 컬렉션으로 남겨 두는 것이 좋습니다. 또한 인보이스를 다루므로 회신에주의를 기울여 필요에 따라 계단식으로 작성해야하므로 Item이 변경되면 Invoice 수정 된 시간이 변경됩니다.