Chovy's Blog

Web Development with Node.js, PHP, Javascript, and HTML5

By

Sorting and Ordering in Rails

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:

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:

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: