Rails ActiveRecord :joins with LEFT JOIN instead of INNER JOIN

Jakub Arnold picture Jakub Arnold · Oct 2, 2009 · Viewed 70.1k times · Source

I have this code

User.find(:all, :limit => 10, :joins => :user_points,
                :select => "users.*, count(user_points.id)", :group =>
                "user_points.user_id")

which generates following sql

SELECT users.*, count(user_points.id) 
FROM `users` 
INNER JOIN `user_points` 
ON user_points.user_id = users.id 
GROUP BY user_points.user_id 
LIMIT 10

is it possible to make LEFT JOIN instead of INNER JOIN other way than User.find_by_sql and manualy typing the query?

Answer

Kylo picture Kylo · Oct 2, 2009

You can try this

User.find(:all, limit: 10,
            joins:  "LEFT JOIN `user_points` ON user_points.user_id = users.id" ,
            select: "users.*, count(user_points.id)", 
            group:  "user_points.user_id")