title: Rails: Nested where clauses in has_many association
body: <p>TLDR: I can't get the where clause to work in a nested (either 1 or 2 levels of nesting down) has_many association</p>
  
  <pre><code>#Author.rb
  has_many :posts
  
  
  #Post.rb
  belongs_to :author
  has_one :post_setting
  
  
  #PostSetting.rb
  #Has attributes like draft (bool), flagged(bool), etc.
  
  belongs_to :post
  </code></pre>
  
  <p>Now, if I am trying to create an association in Author which finds all the posts where post_setting.draft = false, for example, like below.</p>
  
  <pre><code>has_many :published_posts,
    -&gt; {
         includes(:post_setting)
         .where(post_setting: {draft: false})
         .distinct
       },
    class_name "Post"
  </code></pre>
  
  <p>That, unfortunately, fails with the following error</p>
  
  <pre><code>PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "post_setting"
  </code></pre>
  
  <p>Alternatively, I'd like to be able to do the following as well - </p>
  
  <pre><code>#Group.rb
  has_many :authors
  has_many :posts,
    -&gt; {
         includes(:post_setting)
         .where(post_setting: {draft: false})
         .distinct
       },
  through: authors
  </code></pre>
  
  <p>In general, I feel I am not very clear on the rules around how where/joins/includes work in associations. Would it be more advisable to create a scope on posts than include that in the <code>has_many</code> in author?</p>
  
  <p>Thank you!</p>
  
  <p>PS. I am using Rails 4.2.5.</p>