Reputation:
How I can to pass an array like generated by a controler with the following code:
tipos= Type.all
@listadotipos=[]
tipos.each do |h|
@listadotipos.push(h.name)
end
The last code generate an array called @listadotipos. This array is passed to a html.erb view and I want to show all array components inside a Select field in the view.
The select field works this:
<%= f.select :make, options_for_select(["option1", "option2"]) %>
How I can do this. Please help me.
Upvotes: 0
Views: 56
Reputation:
This are the solution. And I dont need code into the controller:
<%= f.select :make, options_from_collection_for_select(Type.all, :id, :name) %>
Thanks all
Upvotes: 0
Reputation: 32933
First of all your controller code can be cleaned up like so:
@listadotipos = Type.all.map(&:name)
Your view code should work if you use the variable instead of your hard coded array:
<%= f.select :make, options_for_select(@listadotipos) %>
Upvotes: 3
Reputation: 12320
Try this in view
<%= f.select :make, Type.all.collect(&:name) %>
For id
<%= f.select :make, Type.all.collect{|type| [type.name, type.id] } %>
Upvotes: 0
Reputation: 118261
With the below code inside the controller :
@listadotipos = Type.all.map { |type| [ type.name, type.id ] }
You can write as below :
<%= f.select :make, @listadotipos %>
Read 3.2 Select Boxes for Dealing with Models guide.
Upvotes: 1