Class: ActiveRecord::PredicateBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record/relation/predicate_builder.rb

Overview

:nodoc:

Class Method Summary collapse

Class Method Details

.build_from_hash(klass, attributes, default_table) ⇒ Object



3
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
32
33
# File 'lib/active_record/relation/predicate_builder.rb', line 3

def self.build_from_hash(klass, attributes, default_table)
  queries = []

  attributes.each do |column, value|
    table = default_table

    if value.is_a?(Hash)
      if value.empty?
        queries << '1=0'
      else
        table       = Arel::Table.new(column, default_table.engine)
        association = klass.reflect_on_association(column.to_sym)

        value.each do |k, v|
          queries.concat expand(association && association.klass, table, k, v)
        end
      end
    else
      column = column.to_s

      if column.include?('.')
        table_name, column = column.split('.', 2)
        table = Arel::Table.new(table_name, default_table.engine)
      end

      queries.concat expand(klass, table, column, value)
    end
  end

  queries
end

.expand(klass, table, column, value) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/active_record/relation/predicate_builder.rb', line 35

def self.expand(klass, table, column, value)
  queries = []

  # Find the foreign key when using queries such as:
  # Post.where(author: author)
  #
  # For polymorphic relationships, find the foreign key and type:
  # PriceEstimate.where(estimate_of: treasure)
  if klass && value.class < Base && reflection = klass.reflect_on_association(column.to_sym)
    if reflection.polymorphic?
      queries << build(table[reflection.foreign_type], value.class.base_class)
    end

    column = reflection.foreign_key
  end

  queries << build(table[column], value)
  queries
end

.references(attributes) ⇒ Object



55
56
57
58
59
60
61
62
63
64
# File 'lib/active_record/relation/predicate_builder.rb', line 55

def self.references(attributes)
  attributes.map do |key, value|
    if value.is_a?(Hash)
      key
    else
      key = key.to_s
      key.split('.').first if key.include?('.')
    end
  end.compact
end