2013-03-15 60 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