Module: ExtendedJoinsImpl

Included in:
ActiveRecord::Base
Defined in:
lib/extended_joins_impl.rb,
lib/extended_joins_impl/version.rb

Constant Summary collapse

VERSION =
"0.0.4"

Instance Method Summary collapse

Instance Method Details

#extended_joins(join_type, table, params = {}) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/extended_joins_impl.rb', line 4

def extended_joins(join_type, table, params={})
  on_key = params[:on] || default_condition(table.table_name, params[:as])

  joins_table_name = params[:as] || table.table_name
  table_arel = table.arel.as(joins_table_name.to_s)

  condition = nil
  on_key.each do |left, right|
    right_value = right.class == Symbol ? table_arel[right.to_sym] : right

    a_condition = self.arel_table[left.to_sym].eq(right_value)
    if condition.present?
      condition = condition.and(a_condition)
    else
      condition = a_condition
    end
  end
  if params[:where].present?
    params[:where].each {|right, value| condition = condition.and(table_arel[right.to_sym].eq(value)) }
  end

  join_node = (join_type == :outer) ? Arel::Nodes::OuterJoin : Arel::Nodes::InnerJoin
  join_state = join_node.new( table_arel, Arel::Nodes::On.new(condition))

  self.joins(join_state).tap do |result_condition|
    result_condition.bind_values = table.bind_values + result_condition.bind_values
  end
end