RoR 3.2.8:是否有HTML5组合框助手?

时间:2012-12-04 21:12:28

标签: ruby-on-rails ruby-on-rails-3 html5

现在,我正在使用form_for.selectoptions_for_select rails帮助程序创建一个包含模型数据的选择框。但是,我真正需要的是像HTML5中引入的组合框:

<input type=text list=browsers >
<datalist id=browsers >
   <option> Google
   <option> IE9
</datalist> 

是否有用于创建此类元素的rails helper?

3 个答案:

答案 0 :(得分:4)

不,但是设置自己的表单构建器帮助器方法来实现这样的结果非常容易,一个简单的例子就是:

应用/ form_builders / combobox_form_builder.rb

 class ComboboxFormBuilder < ActionView::Helpers::FormBuilder
  include ActionView::Context # for nested content_tag
  include ActionView::Helpers::FormTagHelper #for sanitize_to_id method access

  def combobox_tag(name, options, opts= {})
     @template.content_tag(:input, :name => name, :id => sanitize_to_id(name), :type => "text", :list => opts[:list_id]) do
       content_tag(:datalist, :id => opts[:list_id]) {options}
     end    
  end    
end

重新启动服务器后,您可以使用表单构建器通过在form_for调用中指定构建器参数来实现新的组合框:

<%= form_for @foo, builder: ComboboxFormBuilder do |f| %>
    <%= f.combobox_tag(:browser, options_for_select(["Firefox", "Chrome", "IE9"]), :list_id => "list")%>
<% end %>

输出HTML:

<input type="text" name="browser" list="list" id="browser">
<datalist id="list">
  <option value="Firefox">Firefox</option>
  <option value="Chrome">Chrome</option>
  <option value="IE9">IE9</option>
</datalist>

请记住,IE&amp; Safari不支持HTML5 Datalist。

答案 1 :(得分:1)

<%= form_for @person do |f| %>
  <%= f.label :first_name, "First Name" %>:
  <%= f.text_field :first_name, list: 'first-name' %>
  <datalist id="first-name">
    <% Person.all.each do |person| %>
      <option value="<%= person.first_name %>"></option>
    <% end %>
  </datalist>
  <%= f.submit %>
<% end %>

你可能也希望做到与众不同:

<% Person.select(:first_name).distinct.each do |person| %>

答案 2 :(得分:0)

仅从我的代码示例:

= form_tag controller:'beer', action: 'create' do
  = text_field :beer, :name, list: 'beer-name'
  %datalist#beer-name
    - Beer.all.each do |beer|
      %option{value: beer.name}