0

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)

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.