简体   繁体   English

是否可以基于Ruby on Rails活动记录中的人工操作进行排序?

[英]Is it possible to sort based on an arthimatic operation in Ruby on rails active record?

I want to order records based on two columns Arthimatic operation. 我想基于两列Arthimatic操作订购记录。

Ex: I has table columns on which I has to do an arthimatic operation and sort based on its value. 例如:我有一些表格列,必须对其进行人工操作并根据其值进行排序。 Let the columns be math, science and total .And table name is UserMark . 假设UserMark math, science and total 。表名称为UserMark Typically my query looks like this 通常我的查询看起来像这样

UserMark.order('(math/total) desc')

This should order the UserMarks based on math/total operation.How could it be done in Ruby on rails? 这应该基于数学/总运算对UserMarks进行排序。如何在Ruby on Rails中完成呢?

You have two possibilities. 您有两种可能性。

You can do sorting in Active Record query itself. 您可以在Active Record查询本身中进行排序。

UserMark.select("math/total as percentage").order('percentage desc')

or 要么

You can do it in ruby method (this method should be in your model). 您可以使用ruby方法(此方法应该在您的模型中)进行。

def percentage
  self.math/self.total
end

def self.sort_by_percentage
  UserMark.all.sort_by(&:percentage).reverse
end

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

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