title: How to force a has_many association using a different column as foreign key
body: <p>Stuck in a - at first sight - simple problem in RoR. I am sure that is easy, but none answer here in SO helped me too much.</p>
  
  <p>I have two ActiveRecord models: <code>Foo</code> has many <code>Bars</code>:</p>
  
  <pre><code>class Foo &lt; ApplicationRecord
      has_many :bars
  end
  
  class Bar &lt; ApplicationRecord
    belongs_to :foo
  end
  </code></pre>
  
  <p>That works like a charm. But I would like to use another field of <code>Foo</code> as foreign_key. The default is <code>foo_id</code> I would like to use <code>custom_id</code> as my foreign key. So I tried this  (as many solutions over the web suggested):</p>
  
  <pre><code>class Foo &lt; ApplicationRecord
      has_many :bars, :foreign_key =&gt; 'custom_id', :class_name =&gt; 'Bars'
  end
  
  class Bars &lt; ApplicationRecord
    belongs_to :foo, :class_name =&gt; 'Foo'
  end
  </code></pre>
  
  <p>But that doesn't work. i.e. ActiveRecord keeps binding <code>Foo</code> to <code>Bars</code> using <code>foo_id</code>.</p>
  
  <p>Note: Including a self.primary_key='custom_id' in Foo would partially work. but I don't think that is a good idea. I want to keep foo_id as the primary key</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>Given the feedback -Thank you guys-, I uploaded that example here <a href="https://github.com/montenegrodr/temporary_repository_ror" rel="noreferrer">https://github.com/montenegrodr/temporary_repository_ror</a> :</p>
  
  <ul>
  <li><a href="https://github.com/montenegrodr/temporary_repository_ror/blob/master/app/models/bar.rb" rel="noreferrer">Bar model</a></li>
  <li><a href="https://github.com/montenegrodr/temporary_repository_ror/blob/master/app/models/foo.rb" rel="noreferrer">Foo model</a></li>
  <li>** <a href="https://github.com/montenegrodr/temporary_repository_ror/blob/master/test/models/bar_test.rb#L8" rel="noreferrer">This test is expected to PASS but it FAILS.</a>**</li>
  </ul>
  
  <p><strong>UPDATE #2:</strong></p>
  
  <p>The answers does not satisfy the question above. Why the test is failing, my assumption is that it shouldn't fail. </p>
  
  <p><strong>UPDATE #3:</strong></p>
  
  <p>There're a couple of new answers I still need to assess. Will do that within 24 hours. Thanks.</p>
  
  <p><strong>UPDATE #4:</strong></p>
  
  <p>Thank you guys for all the answers. But none of them satisfied the criteria. I need to have that test passing. If it is not possible, can someone explain why? Is it a rails constraint?</p>