0

I have the following models:

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

The question is how to fetch all income Items for the given company?

Something similar to company.items.expense

4

1 回答 1

-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.expensesand company.incomes

根据您的使用情况,您可能会发现最好嵌入Item其中Invoice或将其保留为单独的集合。此外,由于您正在处理发票,请记住要小心您的回调并在必要时使它们级联,因此Invoice如果更改时间,则修改时间Item会更改。

于 2012-08-22T20:30:03.540 回答