A checkbox is a user interface element that allows a user to select or deselect a Boolean value. This method takes two arguments: the attribute name (as a symbol or string) and an options hash. You can use the options hash to specify additional attributes for the checkbox input, such as the value or checked status. In Ruby on Rails, checkboxes are often used in forms to allow users to toggle Boolean values or select multiple items.

Here are some examples of how to use checkboxes in a Ruby on Rails application:

  1. Simple Form Checkbox
    <%= simple_form_for @model do |f| %>
    <%= f.input :attribute_name, as: :boolean, label: "My Checkbox Label" %>
    <%= f.submit %>
    <% end %>
    
  2. Form Checkbox with Custom HTML Attributes
    <%= form_for @model do |f| %>
      <%= f.check_box :attribute_name, class: "custom-class", data: { custom_data: "value" } %>
      <%= f.label :attribute_name, "My Checkbox Label" %>
      <%= f.submit %>
    <% end %>
    
  3. Multiple Checkboxes with Active Record Collection
    <%= form_for @model do |f| %>
      <% @options.each do |option| %>
        <%= f.check_box :attribute_name, { multiple: true }, option.id, nil %>
        <%= option.name %>
      <% end %>
      <%= f.submit %>
    <% end %>
    
  4. Checkbox with AJAX Update
    <%= form_for @model, remote: true do |f| %>
      <%= f.check_box :attribute_name, { onchange: "this.form.submit();" } %>
      <%= f.submit %>
    <% end %>
    

    NOTE: Each of these examples, @model and :attribute_name should be replaced with the appropriate variable and attribute names for your specific use case.

Need Help With Ruby On Rails Development?

Work with our skilled Ruby on Rails developers to accelerate your project and boost its performance.

Hire Ruby on Rails Developer

Support On Demand!

Related Q&A