Rails ActiveRecord :joins with LEFT JOIN instead of INNER JOIN

Ruby on-RailsActiverecordJoinLeft JoinInner Join

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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")

Solution 2 - Ruby on-Rails

Just for future reference, adding :all gives a deprecated message. In later versions of rails you can simply chain the methods like this:

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

OR use a scope like this:

scope :my_scope_name_here, -> { 
        joins("LEFT JOIN `user_points` ON user_points.user_id = users.id")
        .select("users.*, count(user_points.id)")
        .group("user_points.user_id")
}

You can also chain .where between the .join and the .select. Hope this helps someone in the future.

Solution 3 - Ruby on-Rails

Rails 5 has a left_outer_joins method. So you can do

User.left_outer_joins(:user_points)

or use the alias

User.left_joins(:user_points)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJakub ArnoldView Question on Stackoverflow
Solution 1 - Ruby on-RailsKyloView Answer on Stackoverflow
Solution 2 - Ruby on-Rails8bitheroView Answer on Stackoverflow
Solution 3 - Ruby on-RailsSanthoshView Answer on Stackoverflow