选择列中具有最大列值的行 [英] Select rows having max column value in rails

查看:196
本文介绍了选择列中具有最大列值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表Person的ActiveRecord(:id,:name,:city_id,:work_id,:date)的数组。例如:

  [< Person id:4,name:John,city_id:10,work_id:1,date:2015 10-10>,
< Person id:5,name:Jack,city_id:11,work_id:2,date:2015-10-08>,
< Person id:8,name :John,city_id:10,work_id:2,date:2015-10-11> ;,
< Person id:9,name:John,city_id:10,work_id:3,date:2015-10-11> ;,]

对于一个特定的人,我想要有最大日期的行。所以,对于Jack,我会得到id = 5的行。对于John,我会得到id = [8,9]的行,因为日期是这些行的最大值。我不能找出一个有效的方法来在Rails中。请帮忙。

解决方案可以使用rails的类方法。



试试这个:

Person.find_all_by_date(self.maximum('date'))



查看一些详情 here。


I have an array of ActiveRecord of table Person (:id, :name, :city_id, :work_id, :date). For eg :

[<Person id: 4, name: John, city_id: 10, work_id: 1, date: 2015-10-10>,
  <Person id: 5, name: Jack, city_id: 11, work_id: 2, date: 2015-10-08>,
  <Person id: 8, name: John, city_id: 10, work_id: 2, date: 2015-10-11>,
  <Person id: 9, name: John, city_id: 10, work_id: 3, date: 2015-10-11>,]

For a particular person, I want the rows with the maximum date. So, for Jack, I'll get row with id = 5. For John, I'll get the rows with id = [8,9] as the date is maximum for these rows. I can't figure out an efficient way to to this in Rails. Please help.

解决方案

You can use maximum class method of rails.

Try this:

Person.find_all_by_date(self.maximum('date'))

See some details here.

这篇关于选择列中具有最大列值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆