RSS
 

Sorting and Ordering in Rails

14 Aug

Example 1: Writing your own sort routine

I originally tried ‘sort_by’, but that only works for existing attributes and apparently in only one direction.

My ‘is_default’ attribute is setup as a boolean and is almost always false, except where I define an image as being the default for a given product.

Converting a boolean to a string and then sorting alphabetically in reverse order is not something I liked nor recommend, but it was the first thing that I got working.

The Admin helper:

module AdminHelper
  def sort_my_pictures(pics)
    pics.sort {|a,b| b.is_default.to_s  a.is_default.to_s }
  end
end

Example 2: Define your own sort method available from the object instance

Defining a method on the model itself is was an improvement over Ex. 1, but still rather cumbersome to have to call it everywhere to get the sorted list of pictures. Definitely starts to break the DRY principle.

I like this method as an alternative because it can be a convenient way to override default sorting as defined in Ex. 3.

The Picture model:

class Picture  'created_at DESC, title DESC, filename ASC')
end

Example 3 (best): Define the ordering when declaring the relationship

I was positive there was a one-liner to do what I wanted, but could not figure out how to word my question or search to reflect what I needed.

FYI: “How do I define the order when declaring a has_many relationship between models with Rails?” would have worked well. Hindsight is 20/20.

The convenience of MVC is starting to come to light!

The Product model:

class Product  'is_default DESC, title'
end
VN:F [1.9.3_1094]
Rating: 3.5/10 (2 votes cast)
VN:F [1.9.3_1094]
Rating: +1 (from 1 vote)
Sorting and Ordering in Rails, 3.5 out of 10 based on 2 ratings
Retweet
 
Comments Off

Posted in Ruby on Rails

 

Comments are closed.