Rails 4 - checkboxes for has_and_belongs_to_many association

后端 未结 3 2026
悲&欢浪女
悲&欢浪女 2020-12-01 12:29

I recently had a problem getting checkboxes to work for a has_and_belongs_to_many (HABTM) association in Rails 4. I was able to find the information on how to get it working

3条回答
  •  無奈伤痛
    2020-12-01 13:03

    The form should have something like this:

    <%= form_for(@kennel) do |form| %>
        ...
        
    Handlers
    <%= hidden_field_tag("kennel[handler_ids][]", nil) %> <% Handler.order(:name).each do |handler| %> <% end %>
    ... <% end %>

    The hidden_field_tag allows the user to uncheck all the boxes and successfully remove all the associations.

    The controller needs to allow the parameter through strong parameters in the permitted_params method:

    params.permit(kennel: [:city, :state
        {handler_ids: []},
        :description, ...
        ])
    

    References:

    • http://railscasts.com/episodes/17-habtm-checkboxes
    • https://coderwall.com/p/_1oejq

提交回复
热议问题