需要一个价值来降低其他人的升序

时间:2013-10-28 05:22:43

标签: ruby-on-rails ruby ruby-on-rails-3 model mysql2

我有一个下拉列表,它在mysql2数据库的products表中有以下数据。

我使用以下模型从db

中获取它

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

我该如何实现?

5 个答案:

答案 0 :(得分:3)

一条没有任何额外条件的衬垫,只是纯粹的订购:

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

有关按字段语法排序的更多信息,请访问:http://www.electrictoolbox.com/mysql-order-specific-field-values/

答案 1 :(得分:0)

首先将dxx添加到product_list。然后以这样的方式查询您的数据:您在结果中排​​除dxx并按升序排序。最后,将结果附加到product_list。

答案 2 :(得分: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}] }

答案 3 :(得分: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

答案 4 :(得分:0)

制作两个数据库查询效率不高,查询中的where条件会使情况更糟,IMO只需返回整个列表

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

然后挑出dxx项并将其插入第一个

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