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

后端 未结 5 512
星月不相逢
星月不相逢 2020-12-14 05:59

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.tea         


        
5条回答
  •  生来不讨喜
    2020-12-14 06:18

    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)
    

提交回复
热议问题