如何在两个字段的 ruby/rails 中排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9143371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I sort in ruby/rails on two fields?
提问by Kamilski81
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?
比如我想按game_date排序,然后如果日期相同,就按团队排序?什么是最好的方法来做到这一点?
@teams = @user.teams
@games = @teams.reduce([]) { |aggregate, team| aggregate + team.games}.sort_by(&:game_date)
回答by Daniel Pittman
The best way would be to have your database do it, but if you want to use Ruby:
最好的方法是让你的数据库来做,但如果你想使用 Ruby:
@games = @data.sort_by {|x| [x.game_date, x.team] }
The sorting behaviour of Arrayis 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.
的排序行为Array是按第一个成员排序,然后是第二个,然后是第三个,依此类推。由于您希望将日期作为主键,将团队作为第二键,这两个数组将按照您想要的方式进行排序。
回答by demas
@teams = @user.teams
@games = @teams.games.order("game_date ASC, team ASC")
回答by atw
@teams = @user.teams
@games = @teams.games.order(game_date: :asc, team: :asc)
回答by Wahaj Ali
Assuming that you have a model which have these two fields
假设您有一个包含这两个字段的模型
Model.all(:order => 'attribute1, attribute2')
Model.all(:order => 'attribute1, attribute2')
Incase the fields are in multiple tables, you can use joins.
如果字段在多个表中,您可以使用连接。
回答by Stone
For those looking to sort an array containing two different objects w/ a differently named date field, you can do this with an attribute alias method in the model.
对于那些希望对包含两个不同对象且具有不同名称的日期字段的数组进行排序的人,您可以使用模型中的属性别名方法来执行此操作。
note: using .sort_by! destructively doesn't work.
注意:使用 .sort_by!破坏性地不起作用。
News.rb
新闻.rb
def release_date
self.publish_date
end
Controller
控制器
@grid_elements = @news + @albums
@grid_elements = @grid_elements.sort_by(&:release_date)

