2011-08-21 42 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

這很好,但人們習慣於像我會說的生日那樣使用下拉菜單。這些年對於想要使用這種選擇器的人來說太遙遠了。 –