1

In Rails, I have an array of hashes (@things) that looks something like this:

[
{"id"=>1, "name"=>"firstThing"}, 
{"id"=>2, "name"=>"secondThing"}, 
{"id"=>3, "name"=>"thirdThing"}
]

I also have an object with a thingId with a value of 2 (@otherThing.thingId = 2). I would like to turn the array into a dropdown with an empty option and with the secondThing option selected (because it has id = 2).

I successfully built this with some if, else and using that to output some <option value... code, then realized that's probably not the Railsy way to do it. Not sure exactly how to railsify this the best way. I have reviewed the documentation at http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html, but I'm not sure how my array of hashes fits in with all of that.

1 Answer 1

2

The options_for_select helper can take an array like this:

[
  ["firstThing", "1"],
  ["secondThing", "2"],
  ["thirdThing", "3"]
]

(The select helper uses options_for_select internally, so, depending on your use case, it makes this even simplier) So all you need is to convert your array of hashes into the above form. For example like this:

arrayForOptions = arrayOfHashes.collect { |item|
  [item['name'], item['id']]
}
Sign up to request clarification or add additional context in comments.

4 Comments

OK, now I have it converted the way you're describing, but the documentation for options_for_select doesn't show how to have the correct id selected based on another variable's value. Do you know how to do that?
the second parameter of the options_for_select call is the id of the element that should be selected.
Got it. In order to get a blank option, I also added .insert(0, "") on my collect.
A blank dropdown option can also be added by using this flag within the input element include_blank: true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.