Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 4 populate dropdown values from database

I have a dropdown in a rails form:

<%= f.select :lists, [["test1", 1], ["test2", 0]] %>

This works fine but how can I make it dynamic. (interacting with model data)

I have a controller with an action containing @list = List.all

How can I populate id and name in my combobox. I've been searching around, but I am unclear about it. Can anyone help>

like image 816
Prabhakaran Avatar asked Oct 06 '13 16:10

Prabhakaran


2 Answers

This worked for me

# view
<%= form.select(:list_id) do %>
    <% @list.each do |l| -%>
      <%= content_tag(:option, l.name, value: l.id) %>
    <% end %>
<% end %>

and

# controller
@list ||= List.all

`

like image 168
Kaushik Avatar answered Oct 20 '22 01:10

Kaushik


You can use options_from_collection_for_select.

<% options = options_from_collection_for_select(@list, 'id', 'name') %>
<%= f.select :all_val,  options %>
like image 37
mechanicalfish Avatar answered Oct 20 '22 01:10

mechanicalfish