Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to left join with Arel?

Tags:

join

ruby

arel

Arel 3.0.2 provides two classes to specify the join type: Arel::Nodes::InnerJoin and Arel::Nodes::OuterJoin and uses InnerJoin as default.

foo = Arel::Table.new('foo')
bar = Arel::Table.new('bar')

foo.join(bar, Arel::Nodes::InnerJoin) # inner
foo.join(bar, Arel::Nodes::OuterJoin) # outer

foo.join(bar, ???) # left

How can you join two tables if you want to produce a left join?

like image 394
unnu Avatar asked Sep 18 '12 10:09

unnu


2 Answers

You can use

foo.join(bar, Arel::Nodes::OuterJoin) # outer

Because LEFT JOIN = LEFT OUTER JOIN. Outer is an option. See here

like image 149
timfjord Avatar answered Oct 27 '22 05:10

timfjord


Here is a full example with rails models for anyone that wants to see.

Took me a couple of hours to figure out so I thought I would share with the world

This assumes you have one model called RssFeed and another called RssFeedUser which is a join model for a has_many :through for a model called User

RssFeed.find_by_sql(
  RssFeed
    .arel_table
    .join(RssFeedUser.arel_table, Arel::Nodes::OuterJoin)
    .on(RssFeed.arel_table[:id].eq(RssFeedUser.arel_table[:rss_feed_id]))
    .where(RssFeedUser.arel_table[:user_id].eq(nil))
    .project('rss_feeds.*')
)
like image 34
Will Avatar answered Oct 27 '22 04:10

Will