title: Populating a self join table in Rails 4
body: <p>I have a product table and a related product table, related works one way:</p>
  
  <pre><code>Product(id: int, name: string)
  RelatedProduct(id: int, product1: int, product2: int)
  </code></pre>
  
  <p>With the following models:</p>
  
  <pre><code>class Product &lt; ActiveRecord::Base
    validates :name, :uniqueness =&gt; true, :presence =&gt; true
    has_many :relations, :class_name =&gt; "RelatedProducts", :foreign_key =&gt; :product1, inverse_of: :source
    has_many :related_products, through: :relations, :source =&gt; :destination
  end
  
  class RelatedProducts &lt; ActiveRecord::Base
    belongs_to :source, :class_name =&gt; "Product", inverse_of: :relations
    belongs_to :destination, :foreign_key =&gt; :product2, :class_name =&gt; "Product"
  end
  </code></pre>
  
  <p>This works if I prepopulate the RelatedProducts table, the show view will correctly display all the related products. What I cannot figure out is how do to populate RelatedProducts from the html?</p>
  
  <pre><code>&lt;%= form_for(@product) do |f| %&gt;
  
    &lt;div class="field"&gt;
      &lt;%= f.label :name %&gt;
      &lt;%= f.text_field :name %&gt;
    &lt;/div&gt;
  
    &lt;div class="related-products field"&gt;
      &lt;h3&gt;Related Products&lt;/h3&gt;
      &lt;%= f.collection_check_boxes :related_products, Product.where.not(id: @product.id), :self, :name %&gt;
    &lt;/div&gt;
  
    &lt;div class="actions"&gt;
      &lt;%= f.submit 'Update Products' %&gt;
    &lt;/div&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>The strong parameters are defined as:</p>
  
  <pre><code>params.require(:product).permit(:name, related_products: [:id, :name])
  </code></pre>