In Rails, how to handle multiple checked checkboxes, just split on the , or?

前端 未结 5 880
遇见更好的自我
遇见更好的自我 2020-12-02 20:43

Curious what the \'rails way\' of handling the situation when a user checks multiple checkboxes (with the same name value), and it gets posted back to the controller.

<
相关标签:
5条回答
  • 2020-12-02 20:49

    Here is an example of view and controller for example where multiple cleaners can be in multiple cities.

    <%= form_for(@cleaner) do |f| %>
      <p>
        <%= f.label :cities %><br />
        <% for city in City.all %>
          <%= check_box_tag "cleaner[city_ids][]", city.id, @cleaner.cities.include?(city) %>
          <%=h city.name %><br />
        <% end %>
      </p>
      <div class="actions">
        <%= f.submit %>
      </div>
    <% end %>
    

    And in controller

    def cleaner_params
      params.require(:cleaner).permit(city_ids: [])
    end
    

    You can find complete tutorial on "rails way" of doing this https://kolosek.com/rails-join-table/

    0 讨论(0)
  • 2020-12-02 20:50

    If you want to use a checked param you have to write this :

    check_box_tag "tag_ids[]", 1, true
    

    And not this :

    check_box_tag 'tag_ids[]', 1, true
    

    It took me a while to figure out, I hope it will help someone.

    0 讨论(0)
  • 2020-12-02 20:53

    In addition to Chuck Callebs answer, I realised that with sending an empty string instead of nil or false as unchecked value, Rails will understand to remove associated ids on an update action:

    <%= f.check_box :tag_ids, {multiple: true}, tag.id, '' %>

    0 讨论(0)
  • 2020-12-02 21:05
    f.check_box :tag_ids, {multiple: true}, 1, nil
    

    Is the right answer:

    Here is the reason, there is a 'multiple: true' option that allows your input to be placed in an array. If there isn't a multiple: true option this will not be allowed.

    0 讨论(0)
  • 2020-12-02 21:08

    The easiest way of doing this is to set those checkboxes up to become an array.

    HTML:

    <input type="checkbox" name="tag_ids[]" value="1" />
    <input type="checkbox" name="tag_ids[]" value="2" />
    <input type="checkbox" name="tag_ids[]" value="3" />
    

    Controller:

    tag_ids = params[:tag_ids]
    

    (Of course, you'd probably be using form_for-based helpers in the view, and therefore mass-assigning the tag IDs. This is just the most generic example.)

    0 讨论(0)
提交回复
热议问题