【问题标题】:How to dynamically create a list of checkboxes in Ruby on Rails?如何在 Ruby on Rails 中动态创建复选框列表?
【发布时间】:2018-11-18 10:02:19
【问题描述】:

我已经通过 SQL 查询(存储在 @name 中)获得了一个名称列表,我可以在我的 .html.erb 文件中循环访问它们。有没有办法在每个循环中动态创建一个唯一的check_box_tag ID?例如,是否可以在每个循环中更新 ind[1] 以为每个 check_box_tag 提供唯一 ID?

<% @names.each_with_index do |n, index| %>
    <% n.each_with_index do |value, ind| %>
        <div class="checkbox">
            <%= check_box_tag :ind[1], true, @tags %>
            <%= label_tag :ind[1], value[1] %>
        </div>
        <% end %>
<% end %>

最终结果是我希望允许用户选中感兴趣的名称旁边的复选框。例如,如果我的 SQL 查询返回名称 Alice、Bob、John 和 Zach,并且用户选择 Bob 和 John,我想获得一个表示以下内容的数组(因为一系列布尔值 1 和 0 很好) :

{"Alice"=>"false", "Bob"=>"true", "John"=>"true", "Zach"=>"false"}

我发现了一个类似的问题,但我还没有设法让它为我工作:Ruby on Rails Forms: how to create a CheckBox Table (or List)

【问题讨论】:

    标签: ruby-on-rails loops checkbox dynamic


    【解决方案1】:

    我设法让它使用以下代码:

    <% @names.each_with_index do |n, index| %>
        <% n.each do |value| %>
            <div class="checkbox">
                <%= check_box_tag "name[#{index}]", true, @tags %>
                <%= label_tag "name[#{index}]", value[1] %>
            </div>
        <% end %>
    <% end %>
    

    我在输出页面上使用&lt;%= params.inspect %&gt; 来显示结果。以下是选择第二个和第三个选项后的参数:

    &lt;ActionController::Parameters {"utf8"=&gt;"✓", "name"=&gt;{"1"=&gt;"true", "2"=&gt;"true"}, "commit"=&gt;"Save", "controller"=&gt;"queries", "action"=&gt;"custom_search"} permitted: false&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-01
      • 2013-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多