Rails 上的复选框 [英] Checkboxes on Rails

查看:23
本文介绍了Rails 上的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<label for="features[]">功能:</label><br><%= check_box_tag 'features[]', 'scenarios' %>场景<br><%= check_box_tag 'features[]', 'role_profiles' %>角色简介<br><%= check_box_tag 'features[]', 'private_messages' %>私人信息<br><%= check_box_tag '功能[]', '聊天室' %>聊天室<br><%= check_box_tag 'features[]', 'forums' %>论坛<br><%= check_box_tag 'features[]', 'news' %>消息<br><%= check_box_tag 'features[]', 'polls' %>民意调查

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

解决方案

您正在查看以下内容:

<label for="features[]">功能:</label><% [ 'scenarios', 'role_profiles', ... , 'polls' ].each do |feature|%><br><%= check_box_tag '功能[]', 功能,(params[:features] || {}).include?(feature) %><%=特征.人性化%><%结束%>

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

<label for="feature_ids[]">功能:</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 %><%结束%>

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?

解决方案

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>

这篇关于Rails 上的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆