Ruby-on-rails Rails 上的复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/621340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checkboxes on Rails
提问by alamodey
What's the correct way of making checkboxes that are related to a certain question in Ruby on Rails? At the moment I have:
在 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>
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?
我还希望能够自动检查以前选择的项目(如果重新加载此表单)。我如何将参数加载到这些默认值中?
回答by vladr
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 Featuremodel, with a featurestable and a has_many :featuresrelationship, you probably want this:
虽然如果你已经有一个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>

