title: Active Record Query Interface. Count, Join & Group
body: <p>I am trying to get all the movies sorted by the number of likes (even if they dont have likes yet). I have the following working sql statement:</p>
  
  <pre><code>      SELECT *, COUNT(case when movie_votes.like = 1 then 1 end) AS count_likes 
        FROM movies 
        LEFT OUTER JOIN movie_votes  
        ON movie_votes.movie_id = movies.id 
        GROUP BY movie_id 
        ORDER BY count_likes;
  </code></pre>
  
  <p>And I want to implement it in my controllers. So far I have:</p>
  
  <pre><code>      Movie.select("*, COUNT(case when 'movie_votes'.'like'=1 then 1 end) AS         count_likes").joins("LEFT OUTER JOIN 'movie_votes' ON 'movies'.'id'='movie_votes'.'movie_id'").group("'movie_id'")
  </code></pre>
  
  <p>Which outputs form console:</p>
  
  <pre><code>     SELECT *, COUNT(case when 'movie_votes'.'like'=1 then 1 end AS count_likes FROM `movies` LEFT OUTER JOIN 'movie_votes' ON 'movie'.'id'='movie_votes'.'movie_id' GROUP BY 'movie_id'
  </code></pre>
  
  <p>AND an Mysql2::Error: You have an error in your SQL syntax;
  Am I doing something wrong no the syntax?</p>