title: Arel, Joins and Rails Queries
body: <p>I've been stuck on a problem recently for a little while and found my way to Arel which looks like it should allow me to do OR's in my queries.</p>
  
  <p>As a starting point I needed to convert an existing Rails 3 query to Arel and that's where I've run into problems.</p>
  
  <p>The following scope and query works as I would expect it to.  It gives me the requests associated with a particular user's ads.</p>
  
  <pre><code>#in the Request class
  scope :responder, lambda { |user| joins(:ad).where(:ads =&gt; { :user_id =&gt; user }) }
  
  Request.responder(303).to_sql
  
  =&gt; "SELECT \"requests\".* FROM \"requests\" INNER JOIN \"ads\" ON \"ads\".\"id\" = \"requests\".\"ad_id\" WHERE (\"ads\".\"user_id\" = 303)"
  </code></pre>
  
  <p>According to doco on the Arel github page and Railscast 215 I should be able to do something like the following to replicate the query with Arel</p>
  
  <pre><code>  requests = Request.arel_table
    ads = Ad.arel_table
    where(requests.join(ads).on(ads[:id].eq(requests[:ad_id])))
  </code></pre>
  
  <p>This results in an error</p>
  
  <pre><code>TypeError: Cannot visit Arel::SelectManager
  </code></pre>
  
  <p>I can do the following in the console though</p>
  
  <pre><code>r = Request.arel_table
  a = Ad.arel_table
  
  r.join(a).to_sql
   =&gt; "SELECT  FROM \"requests\" INNER JOIN \"ads\" "
  </code></pre>
  
  <p>So it looks like it's forming the SQL request, however when you put that in a where</p>
  
  <pre><code>Request.where(r.join(a)).to_sql
  </code></pre>
  
  <p>I get the following</p>
  
  <pre><code>TypeError: Cannot visit Arel::SelectManager....
  </code></pre>
  
  <p>I've tried doing other Arel actions within the where and it works (e.g.)</p>
  
  <pre><code>Request.where(r[:status].eq(nil)).to_sql
   =&gt; "SELECT \"requests\".* FROM \"requests\" WHERE (\"requests\".\"status\" IS NULL)"
  </code></pre>
  
  <p>This is a little beyond my growing rails/ruby knowledge. Any ideas?</p>
  
  <p>Thanks in advance.</p>