views:

123

answers:

2

Hi,
I am fairly new to RoR and hacking on a small application. In order to display existing values of some model column in a form, I currently do:

<% form_for([@testbox, @testitem]) do |f| %>
  <%= f.label :sortkey %><br />
  <%= f.collection_select :sortkey, Testitem.groups , :sortkey, :sortkey, {:include_blank => true}  %>
<% end %>

In the model Testitem I have:

def Testitem.groups
  return find_by_sql("SELECT DISTINCT sortkey from testitems; ")
end

I am sure there is a more elegant solution to this? I have tried find(:all).sortkey.unique but that throws undefined method 'sortkey' for #<Array:0x59d1b60>

+4  A: 

This accomplishes the same thing but I'm not sure it's any more elegant:

Testitem.find(:all, :select => "DISTINCT sortkey")
Patrick Robertson
+1 for that, it's at least more elegant as I don't have to write a complete SQL statement. Let's see if there is something even better.
jhwist
+1  A: 

It's probably much faster to do it Patrick Robertson's way. You can also do it with the group option:

Testitem.find(:all, :group => "sortkey")

using the :select option will put the DISTICT sortkey into the SQL query, while using :group adds GROUP BY sortkey. I don't know which one is faster.

You could also do it by just returning the strings of sortkey as well:

Testitem.find(:all).map(&:sortkey).uniq

This is probably slower because it will retrieve all the items and do the filtering on the Ruby side instead of the SQL side.

jamuraa