Checkboxes on Rails

白昼怎懂夜的黑 提交于 2019-12-19 05:47:18

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/621340/checkboxes-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!