title: ActiveRecord has_many through a scoped association with arg
body: <p>I've seen a number of answers to questions that address how to use scope blocks in ActiveRecord associations that include passing the object itself into the block like ...</p>
  
  <pre><code>class Patron &lt; ActiveRecord::Base
    has_many :bars, 
             -&gt;(patron) { baz: patron.blah },
             foreign_key: :somekey,
             primary_key: :somekey
  end
  
  class Bar &lt; ActiveRecord::Base
    belongs_to :patron,
               -&gt;(bar) { blah: bar.baz },
               foreign_key: :somekey,
               primary_key: :somekey
  end
  </code></pre>
  
  <p>The usage of the explicit PK and FK here is due to the legacy relationship between the underlying tables. There are many hundreds of millions of "patrons" in the production system.</p>
  
  <p>As a point of clarification re @TJR - the relationship between Patron and Bar is actual a compound foreign key on the fields :somekey and :baz (or :blah in the reverse direction). ActiveRecord's :foreign_key option doesn't allow arrays.</p>
  
  <p>I've discovered that unfortunately this prevents subsequent has_many :throughs from working as expected.</p>
  
  <pre><code>class Patron &lt; ActiveRecord::Base
    has_many :bars,
             -&gt;(patron) { baz: patron.blah },
             foreign_key: :somekey,
             primary_key: :somekey
    has_many :drinks, through: :bars
  end
  </code></pre>
  
  <p>Using the through association produces errors like ... </p>
  
  <blockquote>
    <p>ArgumentError:
           wrong number of arguments (0 for 1)</p>
  </blockquote>
  
  <p>The association between bar and drinks is a classic has_many with the standard foreign and primary key (bar_id, id).</p>
  
  <p>I have come up with some ugly work arounds that allow me to accomplish the desired functionality but the whole thing smells terrible. So far the best of these look like</p>
  
  <pre><code>class Patron &lt; ActiveRecord::Base
    has_many :bars, 
             -&gt;(patron) { baz: patron.blah },
             foreign_key: :somekey,
             primary_key: :somekey
    def drinks
      bars.drinks
    end
  end
  </code></pre>
  
  <p>I've received the existing Bar class and it consists of many hundreds of millions of records, as I previously mentioned, making a database side change difficult.</p>
  
  <p>Some posts seemed to suggest a dynamic string evaluation inside the proc to avoid having to pass in the current patron object - but as mentioned in other posts, this doesn't work.</p>
  
  <p>Please advise me on what I might do to get the has_many through relationship working.</p>