5

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.

1
  • You may want to read through this other post. :) Commented Apr 1, 2013 at 19:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.