Home > Back-end >  Ruby On Rails - Form Select info from database
Ruby On Rails - Form Select info from database

Time:07-29

I have this line of code:

<%= f.select(:state, :id, Location.all.collect { |l| [ l.location, l.id] }, {:class => "form-select"}) %>

but it keeps throwing a: no implicit conversion of Array into Hash

CodePudding user response:

Let’s say you want to be able to select the state and it's id as a part of your params hash.

Rails provides select_tag helper in conjunction with the options_for_select helper so you can create these in your view by just iterating over collection.

options_for_select expects a very specific input – an array of arrays which provide the text for the dropdown option and the value it represents. This is great, because that’s exactly what your part of code does Location.all.collect { |l| [ l.location, l.id] }

Example:

<%= f.select(:state, options_for_select(Location.all.collect { |l| [ l.location, l.id] }),{:class => "form-select"}) %>

So, options_for_select(Location.all.collect { |l| [ l.location, l.id] }) will create a couple of option tags, one for each choice, like this: options_for_select([["choice1",1],["choice2",2]])

Also, if you want to avoid the options_for_select option, you can you use generic select helper.

  • Related