Create/Update Multiple Associated Records with Checkboxes, Fix

Instead of writing a tutorial myself, I'm just going to recommend reading this post:
http://millarian.com/rails/quick-tip-has_many-through-checkboxes/

Essentially creating something like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<%= form_for :interests, html: {id: "interests_form"} do |f| %>
  <div class="field">
    <%= f.label :interests %><br />
    <%= hidden_field_tag 'user[interest_ids][]', '' %>

    <% @interests.each do |interest| %>
      <div class="interest_option" >
        <%= check_box_tag 'user[interest_ids][]', interest.id, @user.interest_ids.include?(interest.id), class:"interest_checkbox" %>
        <div class="interest_tag" ><%= label_tag interest.name %></div>
      </div>
    <% end %>

  </div>
<% end %>

What I wanted to note here is that, in Millarian, the author suggested the following line in the controller to update the form with not checkboxes selected:

1
@user.attributes = {'group_ids' => []}.merge(params[:user] || {})

This, however, no longer works in Rails 5, so you see in my example - line 4, I've added a hidden field of value "" (nil) which would update the record to no associations when all checkboxes are left empty.

Comments

Popular posts from this blog

I18n Country & City Select Fields - Reconstructing Carmen-Rails from Scratch

(Re: Pagination, You're doing it wrong) - Fixing Duplicate/Missing Records in Infinite Scrolling + Pagination by Hacking the Kaminari Gem

Sending an Email Confirmation Link with the Right Locale (with Devise)