The more you know


One of the problems I knew I would have with using Rails is that I don’t know a thing about Ruby or Rails. That’s the point – I wanted to learn at least the outlines of the language, and I learn best when I’ve got a project to use as an excuse to learn things. And since my method of learning this stuff has so far been randomly googling stuff as I need it, I was bound to run across different ways of doing things.

For example, when I wanted to create a drop-down select box, I followed these steps:

  1. create a find_all_whatever method in whatever.rb model class
  2. initialize a @whatevers variable in the controller using the find_all method
  3. define a select object on the form that referenced @whatevers


Turns out that this is at least partly unnecessary. I found this code:

<%= f.select (:whatever_id, Whatever.all.collect {|p| [p.name, p.id]}) %>

This makes use of the Ruby collect method of the Enumerable mixin to return an array that can be used to populate the selection box.

One problem: the “whatevers” are not sorted, but instead are returned in whatever order they were entered. That’s easy enough to get around – the sort method of the Enumerable mixin can be used. In my case, each of my model classes has a field named “name”, so something like this works:

<%= f.select (:whatever_id, Whatever.all.sort{|a, b|a.name <=> b.name}.collect {|p| [p.name, p.id]}) %>

Basically we’re defining the comparison to use for the sort in the parameters passed to the sort method. Another approach is to shorten this:

<%= f.select (:whatever_id, Whatever.all.sort.collect {|p| [p.name, p.id]}) %>

and define a comparison in the whatever.rb model class:

def <=> (another)
    self.name <=> another.name
end