2011-01-05 165 views
1

Product具有以下屬性:Rails:如何過濾和分類產品?

  • 模型
  • 價格

Model屬於:

  • 品牌

鑑於@products,如:

Shop Brand Model Price 
---- ----- ----- ----- 
Ebay Sony  S-100 500 
Ebay Sony  S-200 1000  (in Target it's cheaper) 
Ebay Dell  D-55  300 
Target Sony  S-100 600   (in Ebay it's cheaper) 
Target Sony  S-200 900 
Amazon Dell  D-33  100 

我想只過濾那些用最低的價格,也就是我期望能獲得:

Shop Brand Model Price 
---- ----- ----- ----- 
Ebay Sony  S-100 500 
Ebay Dell  D-55  300 
Target Sony  S-200 900 
Amazon Dell  D-33  100 

,最好通過Brand進行排序,然後通過Model

Shop Brand Model Price 
---- ----- ----- ----- 
Ebay Sony  S-100 500 
Target Sony  S-200 900 
Amazon Dell  D-33  100 
Ebay Dell  D-55  300 

我該怎麼做?

回答

0

你對數據庫特定的排序感到滿意嗎?

@products.order('brand_id, price') 

編輯:過濾器和秩序

EDIT2:不是指數,而是一羣由模型

EDIT3:排序品牌,然後再模擬

EDIT4:不要停止,直到有範圍改進。更好的多字段排序

def lowest_priced(products) 
    # All products are grouped by the model (key is model, value is array of products belonging to that model) 
    per_model = products.group_by{|x|x.model} 
    # Hash of lowest products per model 
    lowest = {} 
    per_model.keys.each do |model| 
    # Find lowest priced product for the model 
    lowest[model] = per_model[model].min_by{|p| p.price} 
    end 
    # Sort the values of the hash 
    return lowest.values.sort_by{|p| [p.model.brand,p.model]} 
end 

您會理想地重構上面的代碼,以便每個函數只有一個責任。

+0

它應該過濾嗎? – 2011-01-05 13:23:56

+0

啊!所以你需要根據model_id進行分組,挑選最低價格然後排序。您可以在數據庫中使用時髦的查詢來做到這一點,但是它是否可移植是很危險的。我會用ruby解決方案更新我的答案(請注意,這意味着所有記錄都將被提取)。 – 2011-01-05 13:32:52

+0

選擇所有記錄並使用所有這些可枚舉的方法將會變得非常緩慢,並帶來大量數據並帶來不必要的複雜性。除非你知道你只處理少量的數據,否則我會不惜一切代價避免這種技術。 – idlefingers 2011-01-05 16:46:59

0

使用searchlogic gem。它會生成很多搜索和排序的範圍。例如

Product.search(:order => :ascend_by_model) 
+0

searchlogic在Rails 3中並不能很好地工作,並且在一段時間內沒有被維護或更新。 – 2011-01-05 13:20:18

0

您應該能夠通過連接表,分組只能得到每一個模型結果和訂購回來你想要的爲了做到這一點在一個單一的查詢。下面列出的是沿着你所需要的線路:

Product.joins(:model => :brand).group("models.name").order("products.price, brands.name, models.name") 

我已經猜到你的品牌的塑造和表有一欄叫名字或東西是什麼型號名稱和品牌名稱存儲在