简体   繁体   English

如何在两个字段中对红宝石/铁矿石进行分类?

[英]How do I sort in ruby/rails on two fields?

For example, I would like to sort by game_date, and then if the date is the same, sort it by team? 例如,我想按game_date排序,然后如果日期相同,则按团队排序? What would be the best way to do this? 最好的方法是什么?

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

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 Array is to sort by the first member, then the second, then the third, and so on. Array的排序行为是按第一个成员,然后第二个,然后是第三个成员进行排序,依此类推。 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. 由于您希望将日期作为主键并将团队作为第二个键,因此这两个数组将按您想要的方式进行排序。

@teams = @user.teams
@games = @teams.games.order("game_date ASC, team ASC")
@teams = @user.teams 
@games = @teams.games.order(game_date: :asc, team: :asc)

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. 如果字段在多个表中,则可以使用联接。

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! 注意 :使用.sort_by! destructively doesn't work. 破坏性地不起作用。

News.rb 新闻.rb

def release_date
    self.publish_date
end

Controller 控制者

@grid_elements = @news + @albums
@grid_elements = @grid_elements.sort_by(&:release_date)

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

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