How to make a check_box checked in rails? How to make a check_box checked in rails? ruby-on-rails ruby-on-rails

How to make a check_box checked in rails?


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.


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


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 %>