首页 > 解决方案 > Rails order by 2 columns not working as expected

问题描述

I have match table which have 2 field match_date and match_time. match_date is of date data type and match_time is of time data type. I want to get all records order by match_date and match_time in ascending order. My query looks like this:

tournament = Tournament.find_by(name: 'Test')
matches = tournament.matches.order(:match_date, :match_time)

when I do matches.first.match_time it's showing match_time is 11:00 am. But I also have match with match_time of 10:40 am. So I was hoping matches.first.match_time to return 10:40 am but I am getting result of 11:00 am. What am I doing wrong ? My query is definitely not giving me desired output.

UPDATE: I also tried to use sort_by but I am getting same output. My sort_by query looks like this

matches = tournament.matches.sort_by{ |a| [a.match_date, a.match_time] }

I also don't have any default_scope in match model.

标签: ruby-on-rails

解决方案


推荐阅读