Reputation: 2833
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) %>
Upvotes: 2
Views: 7792
Reputation: 11915
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
Upvotes: 2