简体   繁体   中英

How to dynamically create a list of checkboxes in Ruby on Rails?

I have obtained a list of names via SQL query (stored in @name ), and I can loop through them in my .html.erb file. Is there a way to dynamically create a unique check_box_tag ID every loop? For example, can ind[1] be updated every loop to provide a unique ID for each check_box_tag?

<% @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 %>

The end result is that I'd like to allow users to check boxes next to names of interest. For example, if my SQL query returns the names Alice, Bob, John, and Zach, and a user selects Bob and John, I would like to obtain an array that represents the following (as a series of Boolean 1's and 0's is fine):

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

I've found a similar question, but I haven't quite managed to get it working for me: Ruby on Rails Forms: how to create a CheckBox Table (or List)

I managed to get it working with the following code:

<% @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 %>

I use <%= params.inspect %> on my output page to display results. Here are the parameters after selecting the second and third option:

<ActionController::Parameters {"utf8"=>"✓", "name"=>{"1"=>"true", "2"=>"true"}, "commit"=>"Save", "controller"=>"queries", "action"=>"custom_search"} permitted: false>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM