Xeen Xeen - 3 months ago 9
Ruby Question

How can I list items in rails for options_for_select?

I'm using

rails 4
and I'd like to list categories in a select drop down menu. How can I do that? I have a form that looks like so:

<%= f.select (:category_id),
options_for_select([
["Maths", 1],
["Physics", 2]
])
%>


but of course, the content has to be dynamic from database, so I tried the following:

options_for_select([
@categories.each do |c|
[c.title, c.id]
end
])


but that outputs
#<Category:randomdigetshere>
if I try to get the same output outside of that
options_for_select
it works and the title / id is being displayed as it should.

What's the right way of doing it?

Answer

You could do

<% categories_array = Category.all.map { |category| [category.title, category.id] } %>
<%= options_for_select(categories_array) %>

or

<%= options_from_collection_for_select(Category.all, :id, :title) %>

You can make it even shorter using collection_select

Comments