3

I'm using a form for create a record in RoR. I've dropdown menu and I don't know how to add a class for styling this element.

Code:

<%= f.collection_select :id, TipusProducte.order(:nom),:id ,:nom, include_blank: false, class: "btn btn-secondary dropdown-toggle" %>

But this class doesn't work, this style is from Bootstrap.

Thanks!

Xavi
  • 67
  • 7

2 Answers2

7

You're doing it right, but you need to separate the hashes:

<%= f.collection_select :id, TipusProducte.order(:nom),:id ,:nom, { include_blank: false }, { class: "btn btn-secondary dropdown-toggle" } %>

Otherwise, it gets interpreted as one hash. The function spec has two object hashes as arguments; the first is for collection options, the second for HTML options.

GoGoCarl
  • 2,519
  • 13
  • 16
  • Leaving this here as it answers the question, but consider @jvillian 's answer as well; you probably don't want to style your select drop-down as a button. – GoGoCarl May 25 '17 at 19:56
1

In the Bootstrap dropdowns docs, the styles are always applied to a button element like this:

<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown button
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item" href="#">Action</a>
    <a class="dropdown-item" href="#">Another action</a>
    <a class="dropdown-item" href="#">Something else here</a>
  </div>
</div>

But collection_select is going to give you select, like this:

<select name="post[author_id]">
  <option value="">Please select</option>
  <option value="1" selected="selected">D. Heinemeier Hansson</option>
  <option value="2">D. Thomas</option>
  <option value="3">M. Clark</option>
</select>    

I'm guessing HTML looks something like:

<select ... class = "btn btn-secondary dropdown-toggle">

And I suppose Bootstrap doesn't know how to do anything with that.

jvillian
  • 19,953
  • 5
  • 31
  • 44