Reputation: 63
I'm building Rails app and trying to order records in database by string column that starts with number.
How can I order by the number at first?
I'd rather ordering as SQL order than sorting by ruby method. Is there any way?
expected order
1.record1
2.record2
10.record10
present order
1.record1
10.record10
2.record2
Upvotes: 0
Views: 924
Reputation: 3290
You could order by
field + 0
to change the data type of field
to a number implicitly:
Model.order("field + 0 ASC")
# similar `string`.to_i in Ruby
# `1.record1` => 1
# `10.record10` => 10
Upvotes: 2