title: Postgres full text search using pg_search - includes(:child_model) breaks the SQL with 'missing FROM-clause entry for table 'child_model'
body: <p>I'm using postgres full text search with the pg_search gem. The search itself is working well, but I need to further filter the results and here are the details:</p>
  
  <pre class="lang-rb prettyprint-override"><code>class Notebook &lt; ActiveRecord::Base
  
   has_many :invites
  
   def self.text_search(query)
    if query.present?
     search(query)
    else
     scoped
    end
  
  end
  </code></pre>
  
  <p>Notebooks Controller:</p>
  
  <pre class="lang-rb prettyprint-override"><code>def index
   if params[:query].present?
    @notebooks = Notebook.text_search(params[:query]).includes(:invites).where("invites.email = :email OR notebooks.access = :access OR notebooks.access = :caccess OR notebooks.user_id = :uid", email: current_user.email, access: "open", caccess: "closed", uid: current_user.id)
   else
    @notebooks = Notebook.includes(:invites).where("invites.email = :email OR notebooks.access = :access OR notebooks.access = :caccess OR notebooks.user_id = :uid", email: current_user.email, access: "open", caccess: "closed", uid: current_user.id)
   end
  </code></pre>
  
  <p>The error I get is 'missing FROM-clause entry for table 'invites'. I have tried many different things including:</p>
  
  <ol>
  <li>replacing 'includes' with 'joins'</li>
  <li>replacing 'includes(:invites) with joins('LEFT JOIN "invites" ON "invites"."email" = "email" ')</li>
  <li>changing the order of the .text_search and the .includes calls.</li>
  <li>adding the includes call in the controller, in the model, in a scope, and in the text_search function definition.</li>
  </ol>
  
  <p>I keep getting the same error, and when using the joins call with SQL it does not filter by invite emails, and shows multiple repeats of each search result.</p>
  
  <p>I would just remove the include(:invites) because the text_search itself is working just fine. But I really need this condition to be included. </p>
  
  <p>Any help would be greatly appreciated. Maybe I'm just getting my SQL call wrong, but I also would like to understand why the .includes(:invites) works without the pg text_search but won't work with it.</p>
  
  <p><strong>Edit #1 - more specific question</strong></p>
  
  <p>I think there are 2 slightly different questions here. The first seems to be some issue with combining pg_search gem and an 'includes(:invites)' call. The second question is what is the equivalent SQL statement that I can use in order to avoid making the 'includes(:invites)' call. I think it should be a LEFT JOIN of some sort, but I don't think I'm making it correctly. In my db, a Notebook has_many invites, and invites have an attribute 'email'. I need the the notebooks with invites that have an email equal to the current_user's email.</p>
  
  <p>Help with either of these would be great.</p>