【问题标题】:Mongoid, complex query, something similar to has_many : throughMongoid,复杂查询,类似于 has_many 的东西:通过
【发布时间】:2012-08-22 08:25:02
【问题描述】:

我有以下型号:

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

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid


    【解决方案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.expensescompany.incomes

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

    【讨论】:

      猜你喜欢
      • 2013-07-25
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-26
      • 2011-04-18
      相关资源
      最近更新 更多