简体   繁体   中英

How to dropdown select in rails form

how to do dropdown select in rails form ?

i tried to

<div class="field">
     <%= f.label :car_id %>
    <%= select("car", "car_id", @cars) %>
  </div>

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

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

  <div class="field">
    <%= f.label :dateofbirth %>
    <%= f.date_select :dateofbirth %>
  </div>

but i get this error

undefined method `empty?' for nil:NilClass

at this line.

  <%= select("car", "car_id", @cars) %>

Try

<%= f.select :car_id, @cars.collect { |car| [car.name, car.id] } %>

You need to set the @cars instance variable in the controller method for the above line of code to work.

I am assuming that car has a name field. Replace name with a field of your Car model that is good enough for a label.

For every option in the select list, name will be set as the label and id will be set as the value .

For more, read the documentation here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM