9

在 Ruby on Rails 中制作与某个问题相关的复选框的正确方法是什么?目前我有:

<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>

我还希望能够自动检查以前选择的项目(如果重新加载了此表单)。我如何将参数加载到这些的默认值中?

4

1 回答 1

15

您正在查看以下内容:

<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>

虽然如果你已经有一个Feature模型,一个features表和一个has_many :features关系,你可能想要这个:

<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>
于 2009-03-07T06:29:53.770 回答