简体   繁体   English

在Rails中可以为模型创建自定义订购方法吗?

[英]Is it possible in Rails to create custom order method for model?

I would like to create something like a new order method for a model in my rails app. 我想在Rails应用程序中为模型创建类似新订购方法的东西。 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. 在列表的开头应该是该列的最高(> 250)和最低(<80)值的记录,其他(平均值在80到250之间)的记录应该在列表的末尾。 Is it possible to do it in rails ? 可以在滑轨中做到吗?

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 使用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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM