hook38 hook38 - 1 year ago 65
Ruby Question

Display text value from dropdown form stored as integer

Following RailsGuides, I am creating a dropdown in form like this:

[['Lisbon', 1], ['Madrid', 2], ...]


which produces a dropdown list like:

<option value="1">Lisbon</option>
<option value="2">Madrid</option>


On my show page, I would like to display the text (
Madrid
) of my stored value instead of the integer (
2
).

The value is stored in the database. This is a live system, which means I cannot change the stored contents (I can, but prefer not to).

I prefer to build the dropdown list from a hash, but since this is the suggested format in RailsGuide, I assume there is a inbuilt helper that can do this. It would be easier if I store the dropdown list as a string, although it will take up a lot of spaces in the database.

I cannot use index since value does not start from
0
, and it might not be in order. I can write a search on this 2 dimensional array, but is there any easier way? Does anyone know the simplest way to solve this?

Answer Source

In situations like this, where you have a selection with a direct mapping from a database value to a display value, and you consistently want to use the display value for presentation, I use this approach:

In your model, declare an array with the mapping relationship:

class Person

  GENDER = [
    ["Male", "m"],
    ["Female", "f"]
  ]

end

In your edit view (the form), you can create the select using this approach:

<%= f.select :gender, Person::GENDER %>

In the show view, you can display using this format:

<%= Person::GENDER.find {|item| item[1] == @person.gender }[0] %>

This approach gives you the ability to control the display order of items in the select, and still be able to render the display value reasonably easily.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download