Rails上的复选框 [英] Checkboxes on Rails
本文介绍了Rails上的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Ruby on Rails中创建与某个问题相关的复选框的正确方法是什么?目前我有:
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?
推荐答案
您正在查看以下内容:
<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
,具有特征
表和 has_many:features
关系,您可能想要:
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>
这篇关于Rails上的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文