如何在两个字段的 ruby​​/rails 中排序? [英] How do I sort in ruby/rails on two fields?

查看:44
本文介绍了如何在两个字段的 ruby​​/rails 中排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比如我想按game_date排序,然后如果日期相同,就按队伍排序?这样做的最佳方法是什么?

For example, I would like to sort by game_date, and then if the date is the same, sort it by team? What would be the best way to do this?

@teams = @user.teams
@games = @teams.reduce([]) { |aggregate, team| aggregate + team.games}.sort_by(&:game_date)

推荐答案

最好的方法是让你的数据库来做,但如果你想使用 Ruby:

The best way would be to have your database do it, but if you want to use Ruby:

@games = @data.sort_by {|x| [x.game_date, x.team] }

Array 的排序行为是按第一个成员排序,然后是第二个,然后是第三个,依此类推.由于您希望将日期作为主键,将团队作为第二键,这两个数组将按您想要的方式排序.

The sorting behaviour of Array is to sort by the first member, then the second, then the third, and so on. Since you want the date as your primary key and the team as the second, an array of those two will sort the way you want.

这篇关于如何在两个字段的 ruby​​/rails 中排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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