Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do a LEFT OUTER JOIN using Rails ActiveRecord?

Tags:

I don't have any ideas. Could you give me any clues (like reference sites). Any help will be appreciated.

Model1: GROUP(id, name) Model2: USER_GROUP_CMB(id, user_id, group_id) 

Expected SQL statement:

SELECT *  FROM groups AS g LEFT OUTER JOIN user_group_cmbs AS cmb              ON g.id = cmb.group_id WHERE cmb.user_id = 1 

I tried to set up associations below but I dont know what to do after this.

class Group < ActiveRecord::Base   has_many :user_group_cmb end  class UserGroupCmb < ActiveRecord::Base   has_many :group end 

Rails Version: 3.1.1

like image 292
zono Avatar asked Nov 06 '11 05:11

zono


2 Answers

I believe an includes will use a LEFT OUTER JOIN query if you do a condition on the table that the includes association uses:

Group.includes(:user_group_cmb).where(user_group_cmbs: { user_id: 1 }) 
like image 167
Ryan Bigg Avatar answered Oct 07 '22 04:10

Ryan Bigg


Rails 5+ allows you to do the following:

Group.left_outer_joins(:user_group_cmb) 

http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-left_joins

like image 45
Diego Plentz Avatar answered Oct 07 '22 05:10

Diego Plentz