Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting numeric-strings in Rails

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.

like image 395
bkorte Avatar asked Apr 01 '13 19:04

bkorte


2 Answers

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

like image 65
Luke Avatar answered Sep 25 '22 01:09

Luke


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.

like image 38
summea Avatar answered Sep 23 '22 01:09

summea