Mongoid,查询获取嵌入字段

时间:2014-10-09 13:56:14

标签: ruby-on-rails mongodb mongoid

如何对集合执行查询与嵌入式

相关联
class SaleInvoice
  include Mongoid::Document
  include Mongoid::Timestamps

   embeds_many :sale_invoice_lines, :order => 'numlig ASC'


  field :code, type: String
end

class SaleInvoiceLine
  include Mongoid::Document
  include Mongoid::Timestamps

  belongs_to :element, primary_key: :code, foreign_key: :codeelem

  field :numlig, type: Integer
  field :codeelem, type: String

end

class Element
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Tree

  has_many :sale_invoice_lines, primary_key: :code, foreign_key: :codeelem

  field :code, type: String
end

查询

  SaleInvoice.only(:_id,:code, "sale_invoice_lines.code","sale_invoice_lines.numlig")
     .where("sale_invoice_lines.codeelem" => {"$in" => Element.all.map {|e| e.code}}).all

如何获取数据sale_invoice_lines.code和sale_invoice_lines.codeelem?

我试试这个

  s[0].sale_invoice_sales[0].code

但我有以下错误

  undefined method `sale_invoice_sales' for #<SaleInvoice:0x56447526>

1 个答案:

答案 0 :(得分:0)

你有:

s = SaleInvoice.only(...).where(...).all

这意味着sSaleInvoice个实例的数组。在SaleInvoice中你有:

class SaleInvoice
  embeds_many :sale_invoice_lines, :order => 'numlig ASC'
end

因此您可以通过以下方式访问嵌入的行:

s.first.sale_invoice_lines

等。