Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails form.select attributes to show different values

I have a model where I store the section parameter as an integer in the database, no section = 0, section1 = 1 and section2 = 2.

I want the user to be able to select the section by it's name, not by the stored value, i.e I want the form select to show 'no section, section1, section2' as options but then store it's corresponding value in the database 0,1 or 2.

   .form-group
      = f.label :section, 'Choose a section'
      = f.select :section,(show 'no section, section1, section2' but store 0,1,2)
like image 282
raphael_turtle Avatar asked Feb 22 '26 14:02

raphael_turtle


1 Answers

you have to pass an array with the options

= f.select :section, [ ["No section",0], ["Section 1",1], ["Section 2", 2] ]

The proper element will be selected according with the value, so if your object has a value for the section = 2, then "Section 2" will be selected when you load the page.

You can take a look to http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-select and http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select for more details

like image 116
Fer Avatar answered Feb 24 '26 06:02

Fer