我想在我的rails应用程序中为模型创建类似新订单方法的东西。此订单方法应该能够将记录与一列进行比较。在列表的开头应该是具有该列的最高(> 250)和最低(<80)值的记录,而其他(具有80到250之间的平均值)的记录应该在列表的末尾。是否可以在铁轨中进行?
答案 0 :(得分:0)
使用普通红宝石
# when order between 0 - 80 and > 250 does not matter
YourModel.all.to_a.sort_by do |record|
if record.order_col < 80 || record.order_col >250
0
else
1
end
end
# when order between 0 - 80 and > 250 does matter
YourModel.all.to_a.sort_by do |record|
if record.order_col < 80 || record.order_col >250
record.order_col
else
record.order_col + YourModel.max(:order_col) + 1
end
end
使用SQL
# with sql
scope :ordered, find_by_sql(%(
SELECT your_model.* FROM your_model where value < 80 OR value > 250 ORDER BY id desc
UNION
SELECT your_model.* FROM your_model where value >= 80 and value <= 250 ORDER BY id desc
))
# can work with mysql
YourModel.select(:field, ..., 'IF (column < 80 OR column > 250, column, column + (SELECT max(column) FROM yourtable ) + 1) as order_column').order('order_column desc')