2011-08-21 67 views
1

因此,我正在运行rails 3.1.0.rc6,并且我很难理解使用模型的下拉列表(选择元素)。模型的Rails 3.x下拉列表

我有以下几点:

<%= form_for @user do |f| %> 
     <div class="input"> 
     <%= f.label :email %> 
     <%= f.text_field :email %> 
     </div> 

     <div class="input"> 
     <%= f.label :password %> 
     <%= f.password_field :password %> 
     </div> 

     <div class="input"> 
     <%= f.label :password_confirmation, "Repeat Password" %> 
     <%= f.password_field :password_confirmation %> 
     </div> 

     <div class="input"> 
     <%= f.label :first_name %> 
     <%= f.password_field :first_name %> 
     </div> 

     <div class="input"> 
     <%= f.label :last_name %> 
     <%= f.password_field :last_name %> 
     </div> 

     <div class="input"> 
     <%= f.label :birthday %> 
     <%= date_select "user", "birthday" %> 
     </div> 

     <div class="input"> 
     <%= f.label :gender %> 
     <%= select_tag :gender, options_for_select([['Male', 'male'], ['Female', 'female']]) %> 
     </div> 

     <div class="submit"> 
     <%= f.submit nil, :class => ['button', 'button_blue'] %> 
     </div> 
    <% end %> 

现在我不知道如何有一个易于使用的生日选择和性别选择。它生成的HTML并不适用于模型保存。

任何帮助将是伟大的!谢谢。

目标:只需要用发布的数据做一个简单的User.create即可。

回答

1

您可以使用select表单生成器助手直接关闭你的“F”变量,例如

f.select(:gender, options_for_select([["Male", "male"],["Female","female"]])) 

这将确保该选择的名称和ID以这样的方式,你的创造意愿产生自动提取。

+0

甜,谢谢! –

1

强烈建议您使用simple_form(基于formtastic)。成千上万的开发人员每天都会使用45个叉,等等,这是大多数组织使用的标准。你永远不会回头它是如此简单(但灵活)。由Jose Valim撰写,他在钢轨上撰写书籍,是社区领导人之一。

https://github.com/plataformatec/simple_form 

小摘录(与模型解决您在下拉菜单的具体问题(选择元素): -

...

Now we have the user form: 
<%= simple_form_for @user do |f| %> 
    <%= f.input :name %> 
    <%= f.association :company %> 
    <%= f.association :roles %> 
    <%= f.button :submit %> 
<% end %> 

Simple enough right? This is going to render a :select input for choosing the :company, and another :select input with :multiple option for the :roles. You can of course change it, to use radios and check boxes as well: 
f.association :company, :as => :radio 
f.association :roles, :as => :check_boxes 

...

您仍然可以使用date_calendar gem作为漂亮的日历弹出日期选择器,并且此Does anyone know any gems/plugins/tutorials related to exporting events to iCal, Google Calendar, Outlook from a Rails application?也可能帮助

+0

谢谢,我会看看!不过,现在,我可能只是使用f.select作为我的解决方案。 –

0

对于你的日期选择,你可以使用jQuery的datepicker,这是非常友好的使用。

首先,如果你写你的表单字段这样

<div class="field"> 
    <%= f.label :birthday %><br /> 
    <%= f.text_field :birthday %> 
</div> 

它会自动给出ID =“user_birthday”(注:小心将其设置为文本字段)。 然后,只需添加一个简单的配置在JavaScript中使用jQuery:

$(document).ready(function() { 

    $.datepicker.setDefaults({ 
     dateFormat: 'dd/mm/yy', 
     firstDay: 1, 
     showOn: 'focus' 
    }); 

    $('#user_birthday').datepicker(); 

}); 
+0

这很好,但人们习惯于像我会说的生日那样使用下拉菜单。这些年对于想要使用这种选择器的人来说太遥远了。 –