title: Has Many 'finder_sql' Replacement in Rails 4.2
body: <p>I've got an association that needs a few joins / custom queries. When trying to figure out how to implement this the repeated response is <code>finder_sql</code>. However in Rails 4.2 (and above):</p>
  
  <blockquote>
    <p>ArgumentError: Unknown key: :finder_sql</p>
  </blockquote>
  
  <p>My query to do the join looks like this:</p>
  
  <pre><code>'SELECT DISTINCT "tags".*' \
  ' FROM "tags"' \
  ' JOIN "articles_tags" ON "articles_tags"."tag_id" = "tags"."id"' \
  ' JOIN "articles" ON "article_tags"."article_id" = "articles"."id"' \
  ' WHERE articles"."user_id" = #{id}'
  </code></pre>
  
  <p>I understand that this can be achieved via:</p>
  
  <pre><code>has_many :tags, through: :articles
  </code></pre>
  
  <p>However if the cardinality of the join is large (i.e. a user has thousands of articles - but the system only has a few tags) it requires loading all the articles / tags:</p>
  
  <pre><code>SELECT * FROM articles WHERE user_id IN (1,2,...)
  SELECT * FROM article_tags WHERE article_id IN (1,2,3...) -- a lot
  SELECT * FROM tags WHERE id IN (1,2,3) -- a few
  </code></pre>
  
  <p>And of course also curious about the general case. </p>
  
  <p>Note: also tried using the proc syntax but can't seem to figure that out:</p>
  
  <pre><code>has_many :tags, -&gt; (user) {
    select('DISTINCT "tags".*')
      .joins('JOIN "articles_tags" ON "articles_tags"."tag_id" = "tags"."id"')
      .joins('JOIN "articles" ON "article_tags"."article_id" = "articles"."id"')
      .where('"articles"."user_id" = ?', user.id)
  }, class_name: "Tag"
  </code></pre>
  
  <blockquote>
    <p>ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column tags.user_id does not exist</p>
    
    <p>SELECT DISTINCT "tags".* FROM "tags" JOIN "articles_tags" ON "articles_tags"."tag_id" = "tags"."id" JOIN "articles" ON "article_tags"."article_id" = "articles"."id" WHERE "tags"."user_id" = $1 AND ("articles"."user_id" = 1)</p>
  </blockquote>
  
  <p>That is it looks like it is trying to inject the <code>user_id</code> onto tags automatically (and that column only exists on articles). Note: I'm preloading for multiple users so can't use <code>user.tags</code> without other fixes (the SQL pasted is what I'm seeing using exactly that!). Thoughts?</p>