我有以下型号:
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.expenses
和company.incomes
。
根据您的使用情况,您可能会发现最好将Item
嵌入Invoice
中,或者将其作为单独的集合。此外,由于您正在处理发票,请记住小心回调,并在必要时使其级联,因此如果Item
发生更改,则Invoice
修改的时间会发生更改。