Question

I have a drop down list which has the following datas in products table in mysql2 database.

I am using the following model to fetch it from db

model.rb

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

products table.

dxx 
bxx
exx
axx
cxx
fxx. 

I want to sort the datas in ascending order. But dxx should come in first. So that my datas could be

dxx
axx
bxx
cxx
exx
fxx

How can I implement this??

Was it helpful?

Solution

One liner without any extra conditions, just pure ordering:

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

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

OTHER TIPS

add dxx to your product_list first. then query your data in such a way that you exclude dxx in your result and ordered as ascending. finally, append that result to your product_list.

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}] }

I would rather make 1 DB query and arrange the items once fetched

(Assuming name of column is product, which has axx, bxx, cxx, dxx and so forth):

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

making two db query is not that efficient, with a where condition in query will make it even worse, IMO just get back the whole list

    product_list = Product.all.map { |p| [p.product, p.id, {title: p.product}] }

then pick out the dxx item and insert it at the first

    idx = product_list.index{|x| x[:title] == 'dxx'}
    dxx_item = product_list.delete_at(idx)
    product_list.insert(0, dxx_item)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top