Skip to content

Commit

Permalink
Expose queries for AssociationQueryValue and PolymorphicArrayValue
Browse files Browse the repository at this point in the history
  • Loading branch information
kamipo committed Apr 9, 2017
1 parent 7b78cf9 commit cc0b566
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 21 deletions.
Expand Up @@ -20,9 +20,7 @@ def initialize(predicate_builder)
end

def call(attribute, value)
table = value.associated_table
queries = { table.association_foreign_key.to_s => value.ids }
predicate_builder.build_from_hash(queries)
predicate_builder.build_from_hash(value.queries)
end

# TODO Change this to private once we've dropped Ruby 2.2 support.
Expand All @@ -40,18 +38,21 @@ def initialize(associated_table, value)
@value = value
end

def ids
case value
when Relation
value.select(primary_key)
when Array
value.map { |v| convert_to_id(v) }
else
convert_to_id(value)
end
def queries
{ associated_table.association_foreign_key.to_s => ids }
end

private
def ids
case value
when Relation
value.select_values.empty? ? value.select(primary_key) : value
when Array
value.map { |v| convert_to_id(v) }
else
convert_to_id(value)
end
end

def primary_key
associated_table.association_primary_key
Expand Down
Expand Up @@ -6,12 +6,7 @@ def initialize(predicate_builder)
end

def call(attribute, value)
table = value.associated_table
queries = value.type_to_ids_mapping.map do |type, ids|
{ table.association_foreign_type.to_s => type, table.association_foreign_key.to_s => ids }
end

predicates = queries.map { |query| predicate_builder.build_from_hash(query) }
predicates = value.queries.map { |query| predicate_builder.build_from_hash(query) }

if predicates.size > 1
type_and_ids_predicates = predicates.map { |type_predicate, id_predicate| Arel::Nodes::Grouping.new(type_predicate.and(id_predicate)) }
Expand All @@ -36,12 +31,20 @@ def initialize(associated_table, values)
@values = values
end

def type_to_ids_mapping
default_hash = Hash.new { |hsh, key| hsh[key] = [] }
values.each_with_object(default_hash) { |value, hash| hash[base_class(value).name] << convert_to_id(value) }
def queries
type_to_ids_mapping.map do |type, ids|
{
associated_table.association_foreign_type.to_s => type,
associated_table.association_foreign_key.to_s => ids
}
end
end

private
def type_to_ids_mapping
default_hash = Hash.new { |hsh, key| hsh[key] = [] }
values.each_with_object(default_hash) { |value, hash| hash[base_class(value).name] << convert_to_id(value) }
end

def primary_key(value)
associated_table.association_primary_key(base_class(value))
Expand Down

0 comments on commit cc0b566

Please sign in to comment.