views:

4522

answers:

1

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?

+3  A: 

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>

Cheers, V.

vladr
undefined local variable or method `features' for #<ActionView::Base:0x228bf5c>
alamodey
Well, what model has the features association, and what variable is it stored into? @article? @product? :)
vladr
Actually, why not post the entire code for your view _and_ action (from the controller) _and_ relevant models?
vladr
This is not mapped directly to any model. As per my original post, I have a question and need several options for it. Then I want to be able to automatically check the options if there are any params to the page.
alamodey
Fine. See the updated **first** example for your particular situation.
vladr
Thank you. That works. But I also want these checkboxes to have text next to them as per my OP. Where is this done?
alamodey
And for params[:features]. Is that a one-to-one mapping between :features => x. Or can I loop through it like params[:features].each do
alamodey
Use <%= feature.humanize %>, see above. And params[:features] is an array, you should have params[:features].include?('forums') if the forums checkbox was checked.
vladr
Thank you very much. Can you show me how to do the same thing, but for radio buttons? http://stackoverflow.com/questions/623051/radio-buttons-on-rails
alamodey