1

我有一个下拉列表,其中包含 mysql2 数据库的产品表中的以下数据。

我正在使用以下模型从数据库中获取它

模型.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

我该如何实现这个?

4

5 回答 5

3

一个班轮没有任何额外的条件,只是纯粹的订购:

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

有关按 FIELD 语法排序的更多信息:http ://www.electrictoolbox.com/mysql-order-specific-field-values/

于 2013-10-28T08:11:27.677 回答
0

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

于 2013-10-28T05:34:50.820 回答
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}] }
于 2013-10-28T05:43:25.697 回答
0

我宁愿进行 1 个 DB 查询并在获取后安排项目

(假设列名为product,有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

高温高压

于 2013-10-28T07:54:19.713 回答
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)
于 2013-10-28T08:01:04.627 回答