Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do checkboxes work in Rails?

I was wondering how check boxes work in Rails? What would the table be inside of the database( integer, string,etc)? How would you give 3 different values to check boxes and the user only can choose 1(favorite color: red,green or blue)?

I'm new to rails and it would help to have an explanation from the beginning to end as i see a lot of examples but they don't explain everything from the start.

Thank you.

like image 466
LearningRoR Avatar asked Oct 11 '22 21:10

LearningRoR


1 Answers

There is a distinction between checkboxes and the database. Checkboxes are HTML. Database is connected to your Models, and it has nothing to do with checkboxes.

When you use a checkbox in your HTML view, your form will send some parameter. By default this parameter will have the value "1" (as String). Rails helpers also create an additional hidden input, which sends the value "0" with the same name as the checkbox input. Parsing the parameters Rails picks the first value, so the given parameter is assigned a value "1" if the checkbox has been checked, and the value "0" if it has not.

Now, the value saved in the database depends on the type of the attribute in your model. If you defined a given field as boolean, then it will be stored as boolean (there is some magic, since the String "0" is not considered 'false' in ruby), if you define the attribute as integer, then it will have the value 1 or 0, and if it's a String, you will have "1" or "0".

About these 3 values for checkbox, I would use a <select> or a radio-button.

Red:   <input type="radio" name="colour" value="red" checked="checked"/>
Green: <input type="radio" name="colour" value="green" />
Blue:  <input type="radio" name="colour" value="blue" />

See the ActionView::Helpers::FormHelper#radio_button method.

like image 158
Arsen7 Avatar answered Oct 20 '22 05:10

Arsen7