title: Find_by_sql as a Rails scope
body: <p>r937 from Sitepoint was kind enough to help me figure out the query I need to return correct results from my database.</p>
  
  <p>What I need is to be able to use this query as a scope and to be able to chain other scopes onto this one.</p>
  
  <p>The query is:</p>
  
  <pre><code>SELECT coasters.*
  FROM (
      SELECT order_ridden,
             MAX(version) AS max_version
      FROM coasters
      GROUP BY order_ridden
  ) AS m
  INNER JOIN coasters
  ON coasters.order_ridden = m.order_ridden
  AND COALESCE(coasters.version,0) = COALESCE(m.max_version,0)
  </code></pre>
  
  <p>I tried making a scope like so:</p>
  
  <pre><code>  scope :uniques, lambda {
      find_by_sql('SELECT coasters.*
                   FROM (
                     SELECT order_ridden,
                            MAX(version) AS max_version
                     FROM coasters
                     GROUP BY order_ridden
                   ) AS m
                   INNER JOIN coasters
                   ON coasters.order_ridden = m.order_ridden
                   AND COALESCE(coasters.version,0) = COALESCE(m.max_version,0)')
    }
  </code></pre>
  
  <p>But when I tried chaining another one of my scopes onto it, it failed. Is there a way I can run this query like a normal scope?</p>