How to make a check_box checked in rails?

67,842

Solution 1

Here's how to do it as of rails 4, I didn't check older documentation.

<%= check_box("tag", tag.id, {checked: true}) %>

This will make the checkbox checked. Of course instead of true you will put in some logic which determines if each one is checked.

Solution 2

If you need the check_box to be checked on new, and correctly filled on edit you can do:

<%= f.check_box :subscribe, checked: @event.new_record? || f.object.subscribe? %>

As I mentioned here

Solution 3

The rails docs do say how to have it checked and it depends on the object. If you don't have an instance object to use with check_box, then your best option is to use the check_box_tag as mentioned. If you do, read on.

Here's the link to the docs on the check_box helper. Basically how this works is that you have to have an instance variable defined. That instance variable must have a method that returns an integer or a boolean. From the docs:

This object must be an instance object (@object) and not a local object. It’s intended that method returns an integer and if that integer is above zero, then the checkbox is checked.

For example, let's assume you have a @tag instance in your view which has an enabled method. The following snippet would cause the checkbox to be checked when enabled is true on the @tag object and unchecked when it is false. To have it enabled by default, set the enabled attribute to true in your controller. The last two variables are the values that you want to submit with the form when the check box is checked and unchecked.

<%= check_box "tag", "enabled", {}, "1", "0" %>

A lot of times, you'll see the check_box helper used with a form builder. So if form_for was used for the @tag instance, you would more than likely use this snippet:

<%= f.check_box :enabled %>

Solution 4

No need of writing checked: true for rails >= 4.0 Simply write

<%= check_box_tag "name", value, true %> # true or false

Solution 5

The check_box_tag instead of check_box has a way to set that it's been checked.

Share:
67,842
user1779563
Author by

user1779563

Updated on April 25, 2021

Comments

  • user1779563
    user1779563 about 3 years

    I made checkboxes using the following rails form helper:

    <%= check_box("tag", tag.id) %>
    

    However, I need to make some of them checked by default. The rails documentation doesn't specify how to do this. Is there a way? How?