2014-10-09 252 views
0

如何在集合關聯嵌入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> 

回答

0

您有:

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

這意味着,sSaleInvoice實例的數組。在SaleInvoice您有:

s.first.sale_invoice_lines 

和這樣的:

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

所以你可以通過訪問嵌入式線。

+0

哦,不... sale_invoice_lines而不是sale_invoice_sales ...我要睡覺了...謝謝你的回答 – Phane 2014-10-09 19:05:59