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

前端 未结 5 953
遇见更好的自我
遇见更好的自我 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| %>
      

    <%= f.label :cities %>
    <% for city in City.all %> <%= check_box_tag "cleaner[city_ids][]", city.id, @cleaner.cities.include?(city) %> <%=h city.name %>
    <% end %>

    <%= f.submit %>
    <% 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/

提交回复
热议问题