0

I have a list of books categories on my db. I can get the value of them inside my controller like this:

@categories = Book.uniq.pluck(:category) #programming, networking, infrastructure

And then, I can pass the value in the view to a drop down menu like this:

<%= s.select :category, options_for_select(@categories) %>

So, my question:

How I can define to be the selected default value of my drop down menu, the second value of the @categories?

robe007
  • 3,523
  • 4
  • 33
  • 59

2 Answers2

0

You can define the default value by using the :selected option:

<%= s.select :category, :selected => params[:id] %>
Deem
  • 7,007
  • 2
  • 19
  • 23
  • Thanks, but I know this. I just need the answer corresponding to my specific situation within my two questions. – robe007 May 05 '17 at 21:19
  • Have you tried @categories.second? Or alternatively, @categories[1] or Category.all.second? – Deem May 05 '17 at 21:22
  • Sorry, but does not works. Always appear the first value selected, and I want the second or the third. – robe007 May 05 '17 at 22:59
0

According to the documentation about options_for_select, the second parameter is the selected value:

options_for_select(container, selected = nil)

So, the answer according to my question is:

<%= s.select :category, options_for_select(@categories, @categories.second) %>

And of course, you can also try with: options_from_collection_for_select

Note: Some credits also to: https://stackoverflow.com/a/2434434/2954267

Community
  • 1
  • 1
robe007
  • 3,523
  • 4
  • 33
  • 59