Xeen Xeen - 5 months ago 17
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),
["Maths", 1],
["Physics", 2]

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

@categories.each do |c|
[c.title, c.id]

but that outputs
if I try to get the same output outside of that
it works and the title / id is being displayed as it should.

What's the right way of doing it?


You could do

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


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

You can make it even shorter using collection_select