I would like to create something like a new order method for a model in my rails app. This order method should be able to compare records by one column. At the beginning of the list should be records with the highest( > 250) and the lowest( < 80) value of that column and others(with avarage value between 80 and 250) should be at the end of list. Is it possible to do it in rails ?
Asked
Active
Viewed 499 times
0
-
Should this happen within the database/SQL for performance reasons or do you want a plain ruby solution? – slowjack2k Aug 16 '16 at 20:23
-
Within SQL will be ok, but if you may give me a hint how to do something like that in plain ruby it would be great. – Mr. XYZ Aug 16 '16 at 20:29
1 Answers
0
With plain ruby
# 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
With 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')

slowjack2k
- 2,566
- 1
- 15
- 23