views:

57

answers:

2

I have the following code:

@posts = Post.joins(:user).joins(:blog).select

which is meant to find all posts and return them and the associated users and blogs. However, users are optional which means that the INNER JOIN that :joins generates is not returning lots of records.

How do I use this to generate a LEFT OUTER join instead?

+3  A: 

By default when you pass ActiveRecord::Base#joins a named association, it will perform an INNER JOIN. You'll have to pass a string representing your LEFT OUTER JOIN.

From the documentation (http://api.rubyonrails.org/classes/ActiveRecord/Base.html): :joins - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed), named associations in the same form used for the :include option, which will perform an INNER JOIN on the associated table(s), or an array containing a mixture of both strings and named associations. If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table‘s columns. Pass :readonly => false to override.

DBA
A: 
@posts = Post.joins("LEFT OUTER JOIN users ON users.id = posts.user_id").joins(:blog).select
Neil Middleton