Class: AssociationScope::Scope::BelongsToReflection

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

Instance Attribute Summary

Attributes inherited from AssociationScope::Scope

#association, #model

Instance Method Summary collapse

Methods inherited from AssociationScope::Scope

#initialize, inject_scopes

Constructor Details

This class inherits a constructor from AssociationScope::Scope

Instance Method Details

#applyObject



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
# 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.options[:class_name]&.constantize || association.camelize.constantize
  foreign_key = reflection_details.options[:foreign_key]
  association_name = association.to_s.underscore.to_sym
  own_table_name = class_name.to_s.pluralize.underscore
  table_name = table_name class_name

  model.class_eval "    scope association.pluralize, -> do\n      if foreign_key.present?\n        class_name\n          .joins(\"JOIN \#{table_name} ON \#{table_name}.\#{foreign_key} = \#{own_table_name}.id\")\n      else\n        class_name\n          .joins(table_name)\n      end\n        .where(table_name => { association_name =>\n          select(\"\#{association_name}_id\".to_sym) })\n        .distinct\n    end\n  RUBY\nend\n", __FILE__, __LINE__ + 1