Mongoid,复杂的查询,类似has_many的东西:through



我有以下型号:

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 的东西

使用嵌入关系不会有任何区别。调用company.items.expense仍然会返回一个错误,因为company.items返回一个Array。

试试这样的东西:

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

然后您可以调用company.expensescompany.incomes

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

最新更新