Using form_tag and collection_select with Rails3

After being away from rails for a while, i’m coming back en version 3 to check it all out again.

I had a problem with how to create a simple select, using the FormHelper.

I had two models, a user and a customer. They are defined as follows:

class User < ActiveRecord::Base
  belongs_to :customer
end
class Customer < ActiveRecord::Base
  has_many :users
end

In my UserController I have an action called new, where I initialize a new user object and fetch all the customers from the database:

class UsersController < ApplicationController
  # Opens the new user view.
  def new 
    @user = User.new
    # fetches all the customers, ordered by their name
    @customers = Customer.order(:name)
  end
end

However, when I wanted to associate the new user and a customer I couldn't remember how this was done. Then I headed over to api.rubyonrails.com and found the FormHelper, which didn't help me much though...
Then I looked at the FormOptionsHelper, which has the method:
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})

In order to use this in my view, I had the following code:

<% form_for @user do |f| %>
<ul>
  <li>
    <%= f.label :customer %>
    <!-- select element here!-->
  </li>
  <li>
    <%= f.label :name %>:
    <%= f.text_field :name %>
  </li>
  <li>
    <%= f.label :email %>:
    <%= f.text_field :email %>
  </li>
  <li>
    <%= f.submit %>
  </li>
</ul>
<% end %>

The method states that it needs an object, a method, a collection, value, text. This resulted in the first try:

<li>
  <%= f.label :customer %>
  <% f.collection_select :user, :customer_id, @customers, :id, :name %>
</li>

Which gave a nice error...

This worked however:

<li>
  <%= f.label :customer %>
  <%= f.collection_select :customer_id, @customers, :id, :name %>
</li>

Why?
Well the form_tag was being done on the user object already, so the first object could be skipped.

Hope you can use it!