Sorting Numeric Strings in Rails

First, a word of caution: I'm pretty new to Ruby and Rails.

I have a string field in my model that references the existing autonomous naming scheme for my client, which are integers separated by decimals. So, "1.1" and "5.10.1.5", etc.

I would like to use the default sorting of Rails by default, but only regular sorting by this field causes such problems:

1 1.10 1.2 1.3

It is clear that I would like to sort 1.10 at the end. Can someone point me in the right direction?

I am using Rails 3.2.10 and Postgres 9.1.4.

+5
source share
2 answers

, , , limit ..

Postgres, , .

default_scope order("string_to_array(num, '.', '')::int[]")

SQL Fiddle

Postgres

+4

Ruby, ( Matthias Reitinger ruby-forum):

arr = arr.sort_by do |x|
  x.split(".").map {|i| i.to_i}
end

arr - .

( , Ruby 1.8.7):

1.1
1.2
1.9
1.10

.

+3

All Articles