代码之家  ›  专栏  ›  技术社区  ›  Simon

如何将嵌套属性与窗体\u一起用于的select方法?

  •  0
  • Simon  · 技术社区  · 16 年前

    我们有一个 user 哪个型号 :has_one detail . 在一个 form_for 一个用户,我需要一个下拉列表来选择用户的详细信息 time_zone .

    我试过了

    <% form_for @user do |f| %>
        ... user stuff ...
    
        <%= f.select :"detail.time_zone", ...other args... %>
    <% end %>
    

    NoMethodError 详细信息。时区。这样做的正确语法是什么?或者如果不可能这样做,我应该怎么做?

    2 回复  |  直到 16 年前
        1
  •  3
  •   Teoulas    16 年前

    别忘了使用 accepts_nested_attributes_for

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

    详细型号:

    class Detail < ActiveRecord::Base
      belongs_to :user
    end
    

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

    用户新建/编辑视图:

    <% 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 %>
    
        2
  •  0
  •   Community Mohan Dere    6 年前

    为什么后面有结肠 f.select ? 也应该是 <%=... 而不是 <%..

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

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

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