2013-03-15 69 views
0

我有嵌入式產品的產品。通過mongoid中的金額訂購

因此,我想有一個價格列表。我正在使用mongoid &錢寶石。不過,我後來添加了新創建的列表(來自外部apis),所以通過mongoid進行排序沒有任何意義。

房源中包含:price。價格是貨幣類型,包含:美元&:貨幣。

listing.rb:

scope :order_on_price, order_by("price.cents" => "desc") 

這並不工作之一:

scope :order_on_price, sort_by{ |price| price[:cents]} 

products_controller.rb(後外部API的加載):

@product.listings = @product.listings.order_on_price 

我在做什麼錯誤?謝謝..

UPDATE:

新增控制檯輸出:

1.9.3-p327 :005 > Product.last.listings 
=> [#<Listing _id: 514374bc98d12b3a3f00a164, created_at: 2013-03-15 19:21:32 UTC, updated_at: 2013-03-15 19:21:32 UTC, price: {"cents"=>3755, "currency_iso"=>"EUR"}, availability: true, scan_id: "513f4cdf3e15fce2eaec43b6">] 
+0

使用'belongs_to' – hwatkins 2013-03-15 19:54:46

+0

將單獨的文件列爲不是,並非基於所有列表。純粹是產品中的那些。 – 2013-03-15 19:55:34

+0

你可以發佈@ product.listings的rails控制檯輸出嗎? – beck03076 2013-03-15 20:44:05

回答

0

如果你必須有上市爲了我會做這樣的事情:

Product.all.each do |product| 
    reordered_listings = product.listings.order_on_price 
    product.listings.clear 
    reordered_items.each { |i| product.listings.create i.attributes } 
end 

這是每次你進入一個新的列表時都會錯誤地輸入順序,所以我可能會在每次檢索產品時對列表進行排序。

0

在Listing類上,定義一個< =>方法。

def <=>(other) 
    other.price <=> price 
end 

現在,你可以參考清單如下:

product.listings.sort 

或定義的方法,listings_by_price:如果您嘗試基於所有目錄訂購,那麼你需要

def listings_by_price 
    listings.sort 
end 
+0

謝謝@tdahlke,但是:它給出了這個錯誤:NoMethodError:未定義的方法'[]'爲#<金錢小數:39899貨幣:歐元> (我道歉順便說一句,我也改變美分 - >小數) – 2013-03-15 21:03:37

+0

我編輯我的答案以說明Money Gem的使用。 – tdahlke 2013-03-18 13:49:33