Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to create a dynamic select in an html.erb ruby

Good morning. I'm a newbie in Ruby and I'm stuck in a little problem.

In a form, I want to make a selection of categories. Categories can be inserted by the users, so the selection have to be dynamic.

I've tried like this:

<div class="input-field">
    <select class="multiple">
      <%= f.select :category, Category.all.collect {|x| [x.name, x.id]} %>
    </select>
</div>

It works, but on chrome console, look like this:

<div class="input-field">
  <select class="multiple"></select>
  <option value="2">Pastasciutta</option>
  <option value="3">Vegetariano</option>
</div>

The category ID was correctly used as value and the list is correctly shown. But, as you see, the "option" is out of the "select" tag. Can you explain me why? And how can I solve this issue? That list is only shown as a list, but I want to flag and unflag x categories.

My version of Ruby -> 2.3.1

----EDIT----

     _form.html.erb
<%= form_for(recipe) do |f| %>
  <% if recipe.errors.any? %>
    <div id="error_explanation">
       <h2><%= pluralize(recipe.errors.count, "error") %> prohibited this recipe from being saved:</h2>

      <ul>
       <% recipe.errors.full_messages.each do |message| %>
         <li><%= message %></li>
       <% end %>
      </ul>
    </div>
  <% end %>

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

  <div class="field">
    <%= f.label :time %>
    <%= f.number_field :time %>
  </div>

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

  <div class="field">
    <%= f.label :recipe %>
    <%= f.text_area :recipe %>
  </div>


  <div class="input-field">
    <%= f.select :category, Category.all.collect {|x| [x.name, x.id]}, {}, class: "multiple" %>
  </div>

  <br>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

And that's what is rendered:

http://prnt.sc/cfqmp6

like image 801
andrepogg Avatar asked Mar 12 '26 01:03

andrepogg


1 Answers

The line:

<%= f.select :category, Category.all.collect {|x| [x.name, x.id]} %>

Is already rendering the <select> tag part of the element, you are duplicating this element by placing the above line inside another <select>. Change this:

<select class="multiple">
  <%= f.select :category, Category.all.collect {|x| [x.name, x.id]} %>
</select>

To this:

<%= f.select :category, Category.all.collect {|x| [x.name, x.id]}, {}, class: "multiple" %>

The last two arguments are the options and html_options to the select tag. See: http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-select

like image 147
DiegoSalazar Avatar answered Mar 14 '26 14:03

DiegoSalazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!