Class: AssociationScope::Scope::BelongsToReflection

Inherits:
Scope
  • Object
show all
Defined in:
lib/association_scope/scope/belongs_to_reflection.rb

Instance Method Summary collapse

Instance Method Details

#apply ⇒ Object



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
# File 'lib/association_scope/scope/belongs_to_reflection.rb', line 6

def apply
  if reflection_details.options[:polymorphic]
    raise PolymorphicAssociationError.new association: association, model: model
  end

  association = @association
  class_name = reflection_details.klass
  inverse_association = inverse_reflection(class_name)

  unless inverse_association
    raise AssociationMissingError.new missing_in: class_name, association: model.to_s.underscore.pluralize
  end

  foreign_key = reflection_details.foreign_key
  validate_scope!(reflection_details)
  association_scope = reflection_details.scope
  owner_key = model.arel_table[foreign_key]
  target_key = class_name.arel_table[reflection_details.association_primary_key]

  model.scope association.pluralize, -> do
    Scope.target_relation(class_name, association_scope)
      .where(target_key.in(reselect(owner_key).arel))
      .distinct
  end
end