Checkboxes on Rails
-
05-07-2019 - |
Question
What's the correct way of making checkboxes that are related to a certain question in Ruby on Rails? At the moment I have:
<div class="form_row">
<label for="features[]">Features:</label>
<br><%= check_box_tag 'features[]', 'scenarios' %> Scenarios
<br><%= check_box_tag 'features[]', 'role_profiles' %> Role profiles
<br><%= check_box_tag 'features[]', 'private_messages' %> Private messages
<br><%= check_box_tag 'features[]', 'chatrooms' %> Chatrooms
<br><%= check_box_tag 'features[]', 'forums' %> Forums
<br><%= check_box_tag 'features[]', 'news' %> News
<br><%= check_box_tag 'features[]', 'polls' %> Polls
</div>
I also want to be able to automatically check the previously selected items (if this form was re-loaded). How would I load the params into the default value of these?
Solution
You are looking at the following:
<div class="form_row">
<label for="features[]">Features:</label>
<% [ 'scenarios', 'role_profiles', ... , 'polls' ].each do |feature| %>
<br><%= check_box_tag 'features[]', feature,
(params[:features] || {}).include?(feature) %>
<%= feature.humanize %>
<% end %>
</div>
Although if you already have a Feature
model, with a features
table and a has_many :features
relationship, you probably want this:
<div class="form_row">
<label for="feature_ids[]">Features:</label>
<% for feature in Feature.find(:all) do %>
<br><%= check_box_tag 'feature_ids[]', feature.id,
@model.feature_ids.include?(feature.id) %>
<%= feature.name.humanize %>
<% end %>
</div>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow