Collection Select

I always fail to remember how to create a simple drop down for my models with a has_many / belongs_to relationship. It’s one of the most basic things you could possibly do with a form, and yet each time I want to hook one up I find myself opening up a tab and googling for it. Well, no more. From now on I’ll say to myself, “Self, you put that on your blog.” So without further ado… collection_select to the rescue!

Let’s say I have a model Nerd that has_many Computers. When I create or edit a computer, I want to select the nerd it belongs_to.

class Nerd
  has_many :computers

class Computer
  belongs_to :nerd

Then in my view for the computer I’d have this:

<% form_for :computer do |f| %>
    <%= f.label :nerd %>
    <%= collection_select(:computer, :nerd_id, Nerd.all, :id, :name) %>
<% end %>