2

I have two tables 'users' and 'lms_users'

class LmsUser
    belongs_to :user
end

class User
    has_one :lms_user
end

When I write User.all(:joins => :lms_user) it joins tables with Inner join.

I want a Left join. How can change this behavior? (I don't want to use SQL commands, only Ruby syntax for this.)

How can I handle this?

Mladen Jablanović
  • 43,461
  • 10
  • 90
  • 113
Moosa
  • 127
  • 6

3 Answers3

0

:joins => "LEFT JOIN lms_users ON lms_users.user_id = users.id"

Liping Huang
  • 4,378
  • 4
  • 29
  • 46
0

You can pull off LEFT JOIN without SQL, using includes, but only if you specify additional constraint (or merely an order clause) which involves a column from joined table(s). So,

User.includes(:lms_user).all

won't generate LEFT JOIN (but two separate queries instead), but

User.includes(:lms_user).where(:lms_user => {:role => 'admin'}).all

would.

More about this on

Mladen Jablanović
  • 43,461
  • 10
  • 90
  • 113
0

User.left_outer_joins(:lms_user) if You are on rails 5+

alexey_the_cat
  • 1,812
  • 19
  • 33