First, a caveat: I'm pretty new to Ruby and Rails.
I've got a string field in my model which references an existing, offline naming scheme for my client, which are integers separated by decimals. So "1.1" and "5.10.1.5", etc.
I'd like to use Rails' default scope sorting but just a normal sort by this field causes issues like this:
1 1.10 1.2 1.3
Clearly, I'd like 1.10 to be sorted at the end. Can anyone point me in the right direction?
I'm using Rails 3.2.10 and Postgres 9.1.4.
You really really don't want to do this sorting in ruby, as you'll lose the ability to chain scopes, paginate results, use limit
correctly, etc.
This is specific to Postgres, but should do exactly what you want.
default_scope order("string_to_array(num, '.', '')::int[]")
SQL Fiddle
Postgres docs
There are multiple ways of sorting this type of thing in Ruby, but here is one possibility (from a post by Matthias Reitinger on ruby-forum):
arr = arr.sort_by do |x|
x.split(".").map {|i| i.to_i}
end
Where arr
is your array.
This ends up sorting these numbers like this (at least as of Ruby 1.8.7):
1.1
1.2
1.9
1.10
More information can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With