Prabhakaran
Prabhakaran

Reputation: 4019

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>

Upvotes: 11

Views: 21146

Answers (3)

Kaushik
Kaushik

Reputation: 151

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

`

Upvotes: 2

Jeff L
Jeff L

Reputation: 141

Don't quite have enough reputation to respond to your question in the thread above @learner but there's a good chance that @overflow didn't have @list defined in his controller.

To solve my case I put my equivalent of @list (in this case @restaurants) in my "def new" method since I was using it to help create new items with associated restaurants.

# GET /specials/new
  def new
    @special = Special.new
    @restaurants = Restaurant.all // Look Here
  end

Additionally, :all_val in the original response should be the parameter you want to pass in to the database. In my case it was :restaurant_id

Upvotes: 3

mechanicalfish
mechanicalfish

Reputation: 12836

You can use options_from_collection_for_select.

<% options = options_from_collection_for_select(@list, 'id', 'name') %>
<%= f.select :all_val,  options %>

Upvotes: 16

Related Questions