Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match an option in select form with boolean values

I have the following piece of code

%br
= f.label :active, 'Status'
= f.select :active, ['Active','Inactive']

Symbol :active is a boolean type var. How can i match Active => 1/True, and Inactive => 0/False , for the database adding.

Sorry for the newbie question, but i can't figure it out.

like image 563
vladCovaliov Avatar asked Jul 11 '12 10:07

vladCovaliov


2 Answers

You can provide a pair of values for each options: first will be used as label (inner text of <option> tag), second will be used as a value attribute:

= f.select :active, [['Active', true], ['Inactive', false]] 

It'll render something like:

<select name="model[active]">   <option value="true">Active</option>   <option value="false">Inactive</option> </select> 

Have a look at the docs for select and options_for_select.

like image 160
KL-7 Avatar answered Sep 21 '22 23:09

KL-7


A small extension of the earlier answer, if you're using a dropdown.

I needed to use "options_for_select." Also, ":selected" stores the value for the next time you return to the form.

<%= f.select(:active, options_for_select([['Active', true], ['Inactive', false]], {:selected => @symbol.active}),:prompt => "Select") %> 
like image 35
Mark Avatar answered Sep 21 '22 23:09

Mark