The most straigt forward way to do an OUTER join in legacy apps is by using a SQL string:
Saving.select(
'savings.*',
'SUM(deposits.amount) AS total_deposits'
)
.joins(:contributions)
.joins(%q{
LEFT OUTER JOINS depostits
ON depostits.contribution_id = contributions.id
})
You can also (mis)use .includes
as it does an outer join:
class Saving
has_many :contributions
has_many :deposits, through: :contributions
end
Saving.includes(:deposits)
.references(:deposits) # forces a single query
.joins(:contributions) # optional - creates an additional inner join
.select(
'savings.*',
'SUM(deposits.amount) AS total_deposits'
)
And you can also use Arel:
module LegacyOuterJoiner
# clunky hack for outer joins in legacy apps.
def arel_outer_joins(association_name, fkey = nil)
raise "This method is obsolete! Use left_joins!" if respond_to?(:left_joins)
other_model = reflect_on_association(association_name).klass
right = other_model.arel_table
fkey ||= "#{other_model.model_name.singular}_id".intern
arel_table.joins(right, Arel::Nodes::OuterJoin)
.on(arel_table[fkey].eq(right[:id]))
.join_sources
end
end
class Deposit
extend LegacyOuterJoiner
end
Saving.select(
Saving.arel_table[Arel.star],
Deposit.arel_table[:amount].sum.as('total_deposits')
)
.joins(:contributions)
.joins(Deposit.arel_outer_joins(:contribution))