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? 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:
@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. 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')
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! destructively doesn't work.
News.rb
def release_date
self.publish_date
end
Controller
@grid_elements = @news + @albums
@grid_elements = @grid_elements.sort_by(&:release_date)