title: Nested form in many to many relationship in rails 4
body: <p>I have a model Contact which has a many-to-many relationship with Company:</p>
  
  <pre><code>class Contact &lt; ActiveRecord::Base   has_many :contactcompanies  
    has_many :companies, through: :contactcompanies
  </code></pre>
  
  <p>Company model:</p>
  
  <pre><code>class Company &lt; ActiveRecord::Base   
    has_many :contactcompanies  
    has_many :contacts, through: :contactcompanies
  </code></pre>
  
  <p>ContactCompany:</p>
  
  <pre><code>class ContactCompany &lt; ActiveRecord::Base
    belongs_to :company
    belongs_to :contact
  </code></pre>
  
  <p>contacts_controller.rb:</p>
  
  <pre><code>def new
    @contact = Contact.new
  
    @all_companies = Company.all
  
    @contact_company = @contact.contactcompanies.build
  end
  </code></pre>
  
  <p>contact create form where I want to have a multiple select for companies:</p>
  
  <pre><code>&lt;%= form_for @contact do |f| %&gt;
  
    &lt;%= f.label :first_name %&gt;
    &lt;%= f.text_field :first_name %&gt;
  
    &lt;%= f.label :last_name %&gt;
    &lt;%= f.text_field :last_name %&gt;
  
    &lt;%= f.label :image_url %&gt;
    &lt;%= f.text_field :image_url %&gt;
  
    &lt;%= f.label :email %&gt;
    &lt;%= f.text_field :email %&gt;
  
    &lt;%= fields_for(@contact_company) do |cc| %&gt;
      &lt;%= cc.label "All Companies" %&gt;
      &lt;%= collection_select(:companies, :id, @all_companies, :id, :name, {}, { :multiple =&gt; true }) %&gt;
    &lt;% end %&gt;
  
    &lt;div class="form-action"&gt;
      &lt;%= f.submit nil, :class =&gt; 'btn btn-primary' %&gt;
      &lt;%= link_to t('.cancel', :default =&gt; t("helpers.links.cancel")),
                  contacts_path, :class =&gt; 'btn' %&gt;
    &lt;/div&gt;                
  &lt;% end %&gt;
  </code></pre>
  
  <p>My issue is when I go to /contacts/new I get this error:
  Circular dependency detected while autoloading constant Contactcompany</p>
  
  <p>Any ideas? I'm searching for hours without success. Thanks</p>