RydelHouse
RydelHouse

Reputation: 235

Custom ordering in ruby on rails

I have a teachers model, which displays teachers list in view, but I want that head of the school will be always top in the view, their helpers next and teachers last.

How I could add a custom sorting trough a form? Maybe there is any javascript plugin which could move or down teachers in the list?

Upvotes: 0

Views: 108

Answers (2)

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

Easiest way is to create a "group" attribute. So:

your head of school with be group => 1
your helpers would be group => 2
your teachers would be group => 3

Then, something like Employee.order(:group).order(:last_name) would order by your groups and then order by last_name.

to have a custom order, add that as your secondary sort.

Upvotes: 1

Taymon
Taymon

Reputation: 25676

In general, you can define an ordering between instances of a Ruby class by doing the following two steps:

  1. include Comparable in the class definition.
  2. Define a method <=> that takes a single parameter, which is another instance of the class. This method should return 1 if the receiver (self) should be considered greater than the other object, -1 if it should be considered lesser, and 0 if they are equal.

This isn't ActiveRecord-specific but I see no reason why it shouldn't work for an ActiveRecord class.

Upvotes: 2

Related Questions