开发者

How do I use a nested attribute with a form_for 's select method?

开发者 https://www.devze.com 2023-01-04 09:32 出处:网络
We have a user model which :has_one detail.In a form_fo开发者_如何转开发r a user, I want a drop-down to select the user\'s details\' time_zone.

We have a user model which :has_one detail. In a form_fo开发者_如何转开发r 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?


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 %>


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消