formsruby-on-rails-4actionviewhelper

Rails 4: collection_select not inserting 'class' attribute?


What am I missing here? I am working with Rails 4.0.0 and trying out the new Bootstrap 3.0.0rc1. I have a simple 'recipe box' app that has a Recipe model and a Category model that feeds a 'category' field on the Recipe. In the recipes#new view, I have the following fields defined:

<h1>Create New Recipe</h1>
<%= form_for @recipe, html: { class: 'form-horizontal' } do |f| %>
<fieldset>
  <legend>Main Information</legend>
  <div class="form-group">
    <%= f.label :name, "Recipe name", class: "col-lg-2 control-label" %>
    <div class="col-lg-6">
      <%= f.text_field :name, class: "form-control" %>
    </div>
  </div>
<div class="form-group">
  <%= f.label :category_id, class: "col-lg-2 control-label" %>
  <div class="col-lg-6">
    <%= f.collection_select :category, Category.all, :id, :name, class: "form-control", prompt: "Select a category" %>
  </div>
</div>
...

The text_field helper renders a properly formatted tag, complete with class attribute. However, no matter how I construct the select or collection_select helpers, I can't seem to get Rails to give me a that contains a class attribute. The code above gives me this:

<select id="recipe_category" name="recipe[category]"><option value="">Select a category</option>

...

So the prompt comes through, but the class attrib does not, so it looks like part of html_options hash is recognized. But the Bootstrap styling isn't applied. Doesn't matter if I use braces {} around the class: "form-control" or not. Doesn't matter if I use parens around the collection_select params or not. Happens with select helper as well.

Can anyone advise? Are you seeing this too?


Solution

  • Try using :

    <%= f.collection_select :category, Category.all, :id, :name, {prompt: "Select a category"}, {class: "form-control"} %>
    

    According to the rails documentation, first comes options and then html options. Remember that html options need to be in braces: {prompt: "Select a category"} or {class: "form-control"}.