Rails - Form Checkboxes
Rails makes outputting a form pretty easy. Unfortunately, like with many things at this point in my Rails journey, the magic seems pretty opaque. One of the things that was confusing in our latest project was adding checkboxes to our forms.
Our goal is to include the following in our form since it is easier for users to checkboxes instead of typing options in manually:
There are two ways to do this:
check_box_tag and 2)
So lets see an example of the first. If we want the HTML output above, we would input:
The first value is the param value and the second is the value. The third is a boolean for whether the box is checked or not by default. Our last two are the options (name and id) and their corresponding values. Since this is a checkbox our user text is separate (you would probably want to wrap that in a label for proper semantics).
If you wanted the checkbox checked by default you would change
true after the value. You can also pass in other HTML options such as
If you had a collection you wanted to make with checkboxes you would need to wrap the first option in a enumerable loop. However, this is where the second method comes to the rescue.
This would result (without the enumerable) in the exact HTML we are looking for for each of our songs. All the options are:
Some helpful links about these: