Godzilla74 Godzilla74 - 3 months ago 9
Ruby Question

Multiple values from select_tag

Is it possible to either extract the text portion of a select tag after it is passed to a controller or do something else crafty with rails to get the value between the

<option></option>
tags?

My raw html is simple:

<select>
<option value></option>
<option value="5">I have a small problem</option>
<option value="10">I have a big problem</option>
<option value="15">I have a massive problem</option
</select>


I'm converting the selected value to integers in my controller which triggers other system calls (such as routing to the correct support person), however, I'd like to be able to also save the text portion into the user's profile for tracking (i.e. `user.issue = "I have a small problem").

Shy of creating some hidden fields and using Javascript, is there another way to get or include the text value when it passes to the controller?

Answer

Here is some advice which is going to be very general since you don't give a lot of specifics in your question. Yes, the HTML should be "the same" no matter what but really it does matter how you create it because that reflects how it integrates into the rest of your app.

I would create a table in the DB called severity with rows something like this:

id | text      | val 
1  | 'small'   | 5
2  | 'big'     | 10
3  | 'massive' | 15

Now instead of doing translations elsewhere like you imply ("I'm converting the selected value to integers in my controller which triggers other system calls") you can use things like:

problem.severity.text
=> 'massive'
problem.severity.val
=> '15'

Using relationships like has_one, belongs_to, etc. you can then leverage these values or words anywhere in your application. Something as simple as:

    <%= f.collection_radio_buttons :user_id, Severity.all, :id, :text %>