title: How to build a record of a many_to_many relation with a form?
body: <p>Say, I have two model in a <code>many to many</code> relationship (without additional attributes), so a simple <code>has_and_belongs_to_many</code> relationship.</p>
  
  <p>For the purpose, let's say I have a <code>user</code> model and a <code>course</code> model.And the corresponding join table <code>courses_users</code> has only the foreign keys <code>user_id</code> and <code>course_id</code> as attributes.</p>
  
  <p>Now I'm listing <em>(say in the show page of the <code>user</code>)</em> all the <code>course</code> and according to if the current <code>user</code> has enrolled or not <em>(i.e. if a record exist in the join table)</em> I display a cross ✘ or a check ✔.<br>
  No problem thus far.</p>
  
  <p>The problem is that I'm unable to make it editable in a form.</p>
  
  <p>I mean <strong>how</strong> can I associate a <strong>form checkbox</strong> with the fact that <strong>if it is checked I build</strong> a relation, and <strong>if not I delete it</strong>?</p>
  
  <p>Thank you very much.</p>
  
  <hr>
  
  <p>Here is my simple models:</p>
  
  <pre><code>class User &lt; ApplicationRecord
    has_and_belongs_to_many :courses
  end
  
  class Course &lt; ApplicationRecord
    has_and_belongs_to_many :users
  end
  </code></pre>
  
  <p>And here is my form attempt but I don't know at all what to do next.<br>
  I thought about checking for the foreign key of the course..</p>
  
  <pre><code>&lt;%= form_with model: @user do |form| %&gt;
    &lt;%= @courses.each do |course| %&gt;
      &lt;%= form.fields_for :courses do |ff| %&gt;
        &lt;%= ff.check_box 'course_id', checked: (@user.courses.include? course.id) %&gt;
        &lt;%= ff.label 'course_id' %&gt;
      &lt;% end %&gt;
    &lt;% end %&gt;
    &lt;%= form.submit %&gt;
  &lt;% end %&gt;
  </code></pre>