views:

38

answers:

2

We have a user model which :has_one detail. In a form_for a user, I want a drop-down to select the user's details' time_zone.

I've tried

<% form_for @user do |f| %>
    ... user stuff ...

    <%= f.select :"detail.time_zone", ...other args... %>
<% end %>

but I get a NoMethodError for detail.time_zone. What's the correct syntax for doing this - or if it's not possible to do it this way, how should I be doing it?

A: 

Why is there a colon after f.select? Also it should be <%=... and not <%..

Assuming you have a 'time_zone' column in your table,

<% form_for @user do |f| %>
    ... user stuff ...

    # args: user object, time_zone method, prioritizing zones(separating list), default
    <%= f.time_zone_select :time_zone, nil, :default => "Pacific Time (US & Canada)", :include_blank => false %>
<% end %>

Additional resource :

http://railscasts.com/episodes/106-time-zones-in-rails-2-1

http://railsontherun.com/2007/12/21/timezone-selection/

Shripad K
Fixed the equals. Thanks for the pointer to time_zone_select. Your example doesn't work, though, because time_zone doesn't belong to user, it belongs to user.detail. How do I specify that?
Simon
I edited my answer. It should work now.
Shripad K
+3  A: 

Don't forget to use accepts_nested_attributes_for in your user model:

class User < ActiveRecord::Base
  has_one :detail
  accepts_nested_attributes_for :detail
end

Detail model:

class Detail < ActiveRecord::Base
  belongs_to :user
end

Users controller:

class UsersController < ActionController::Base
  def new
    @user = User.new
    @user.build_detail
  end
end

User new/edit view:

<% form_for @user do |u| %>
  <% u.fields_for :detail do |d| %>
    <%= d.select :country, Country.all.map { |c| [c.name, c.id] }
    <%= d.time_zone_select :time_zone %>
  <% end %>
<% end %>
Teoulas