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?
Either you use the check_box_tag or the f. check_box inside a form builder, plus you have to add a label to display it. The construct you are using just generate the <input type="checkbox" value="something" /> and not the label, that you have to add, just like text or with a <%= label_tag 'whatever' %> .
The simplest way to create a checkbox in HTML is by using the input tag. We have set the input type to “checkbox” as you can see in the example code. The name attribute lets us give a name to the checkbox, and with the value attribute, we specify the value it holds.
The <input type="checkbox"> defines a checkbox. The checkbox is shown as a square box that is ticked (checked) when activated. Checkboxes are used to let a user select one or more options of a limited number of choices.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With