在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>
我还希望能够自动检查以前选择的项目(如果此表格已重新加载)。如何将参数加载到这些参数的默认值中?
最佳答案
您正在查看以下内容:
<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>