2013-10-28 55 views
1

我有一個下拉列表,它在mysql2數據庫的產品表中有以下數據。需要一個值先降低其他人的升序

我使用下面的模型從資料庫

model.rb

def self.all_products 
product_list = product.all.map { |p| [p.product, p.id, {title: p.product}] } 
end 

產品表拿來。

dxx 
bxx 
exx 
axx 
cxx 
fxx. 

我想按升序排列數據。但是dxx應該先進來。因此,我的數據可能是

dxx 
axx 
bxx 
cxx 
exx 
fxx 

我該如何實現?

回答

3

一個內襯插件它沒有任何額外的條件,只是純粹的順序:

product.order("FIELD(product,'dxxx') desc, product").map { |p| [p.product, p.id, {title: p.product}] }

更多order by FIELD syntax here:http://www.electrictoolbox.com/mysql-order-specific-field-values/

+0

dhanakar-undefined方法'訂單'爲# Sam

+0

謝謝。從上面的代碼中刪除所有代碼後,它工作正常。這是正確的代碼。 product.order(「FIELD(product,'dxxx')desc,product」)。map {| p | [p.product,p.id,{title:p.product}]} – Sam

+0

@Sam更新了答案。謝謝。 –

0

首先將dxx添加到您的product_list。然後以這樣一種方式查詢數據,即在結果中排​​除dxx並按升序排序。最後,將該結果附加到您的product_list。

0
product_list = product.all(:order=>"product ASC", :conditions=>"product not like 'd%'").map { |c| [p.product, p.id, {title: p.product}] } 

product_list += product.all(:order=>"product ASC", :conditions=>"product like 'd%'").map { |c| [p.product, p.id, {title: p.product}] } 
+0

@ shiva-什麼是d% – Sam

+0

其所謂的「通配符」表示anyword以「d」開頭 – shiva

+0

這似乎工作。它僅按升序排序 – Sam

0

我寧願1個DB查詢並安排項目一旦獲取

(列的假設名稱爲產品,其中有AXX,BXX,CXX,DXX等等)

def self.all_products 
    product_list = product.order("product ASC").map { |p| [p.product, p.id, {title: p.product}] } 
    deleted_obj = nil 
    product_list.delete_if {|p| deleted_obj = p if p[1] == 'dxx'} 
    product_list.unshift(deleted_obj) 
    product_list 
end 

HTH

0

使2分貝查詢是不是有效的,具有其中查詢條件會使事情變得更糟,IMO剛剛找回whol Ë列表

​​

然後挑選出DXX項目,並在第一

idx = product_list.index{|x| x[:title] == 'dxx'} 
    dxx_item = product_list.delete_at(idx) 
    product_list.insert(0, dxx_item) 
+0

引發此錯誤。沒有將符號隱式轉換爲整數 – Sam

+0

哦,這是我的錯,這裏的代碼行x [:title] =='dxx'應該改爲x [2] [:title] ==' dxx' – nickcen