How to Use Checkbox in Form Rails in Ruby on Rails
check_box helper inside a form builder to add a checkbox input. It automatically handles the checked and unchecked states and submits the value to the controller for processing.Syntax
The check_box helper is used inside a form builder like form_with or form_for. It takes the attribute name and optional options.
- attribute: The model attribute linked to the checkbox.
- options: Hash for HTML options like
checked,disabled, orclass. - checked_value: Value submitted when checked (default is "1").
- unchecked_value: Value submitted when unchecked (default is "0").
<%= form_with model: @user do |form| %>
<%= form.check_box :subscribe_newsletter, {}, "yes", "no" %>
<%= form.label :subscribe_newsletter, "Subscribe to newsletter" %>
<% end %>Example
This example shows a form with a checkbox for a User model's subscribe_newsletter boolean attribute. When the form is submitted, the controller receives "yes" if checked or "no" if unchecked.
# app/views/users/_form.html.erb
<%= form_with model: @user do |form| %>
<div>
<%= form.label :subscribe_newsletter, "Subscribe to newsletter" %>
<%= form.check_box :subscribe_newsletter, {}, "yes", "no" %>
</div>
<div>
<%= form.submit "Save" %>
</div>
<% end %>
# app/controllers/users_controller.rb
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
redirect_to @user, notice: "User created successfully."
else
render :new
end
end
private
def user_params
params.require(:user).permit(:subscribe_newsletter)
end
endCommon Pitfalls
One common mistake is forgetting that unchecked checkboxes do not send any value by default, which can cause the attribute to be nil instead of false. Rails solves this by sending a hidden field with the unchecked_value. Another pitfall is not permitting the checkbox attribute in strong parameters, causing it to be ignored.
Also, avoid manually adding a hidden field for unchecked values; the check_box helper does this automatically.
<!-- Wrong: Missing unchecked value, checkbox may not submit false --> <%= form.check_box :subscribe_newsletter %> <!-- Right: Rails adds hidden field automatically --> <%= form.check_box :subscribe_newsletter, {}, "1", "0" %>
Quick Reference
| Usage | Description |
|---|---|
| form.check_box :attribute | Creates a checkbox linked to model attribute with default values (checked: "1", unchecked: "0") |
| form.check_box :attribute, {}, "yes", "no" | Checkbox with custom checked and unchecked values |
| params.require(:model).permit(:attribute) | Permit checkbox attribute in controller strong parameters |
| form.label :attribute, "Label text" | Adds a label for the checkbox for accessibility |