-
Notifications
You must be signed in to change notification settings - Fork 21.4k
/
association_query_value.rb
61 lines (51 loc) · 1.43 KB
/
association_query_value.rb
1
2
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# frozen_string_literal: true
module ActiveRecord
class PredicateBuilder
class AssociationQueryValue # :nodoc:
def initialize(associated_table, value)
@associated_table = associated_table
@value = value
end
def queries
[ associated_table.join_foreign_key => ids ]
end
private
attr_reader :associated_table, :value
def ids
case value
when Relation
relation = value
relation = relation.select(primary_key) if select_clause?
relation = relation.where(primary_type => polymorphic_name) if polymorphic_clause?
relation
when Array
value.map { |v| convert_to_id(v) }
else
convert_to_id(value)
end
end
def primary_key
associated_table.join_primary_key
end
def primary_type
associated_table.join_primary_type
end
def polymorphic_name
associated_table.polymorphic_name_association
end
def select_clause?
value.select_values.empty?
end
def polymorphic_clause?
primary_type && !value.where_values_hash.has_key?(primary_type)
end
def convert_to_id(value)
if value.respond_to?(primary_key)
value.public_send(primary_key)
else
value
end
end
end
end
end