Class: PluckMap::AssociationScope::Rails50

Inherits:
Current
  • Object
show all
Defined in:
lib/pluck_map/association_scope.rb

Overview

In Rails 5.0, ‘apply_scope` isn’t extracted from ‘last_chain_scope` and `next_chain_scope` so we have to override the entire methods to extract `apply_scope` and bypass type-casting.

Refer to github.com/rails/rails/blob/v5.0.7.2/activerecord/lib/active_record/associations/association_scope.rb#L61-L94

Instance Method Summary collapse

Methods inherited from Current

#scope

Instance Method Details

#apply_scope(scope, table, key, value) ⇒ Object



82
83
84
85
86
87
88
# File 'lib/pluck_map/association_scope.rb', line 82

def apply_scope(scope, table, key, value)
  if value.is_a?(Arel::Attributes::Attribute)
    scope.where(table[key].eq(value))
  else
    scope.where(table.name => { key => value })
  end
end

#last_chain_scope(scope, table, reflection, owner, association_klass) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/pluck_map/association_scope.rb', line 51

def last_chain_scope(scope, table, reflection, owner, association_klass)
  join_keys = reflection.join_keys(association_klass)
  key = join_keys.key
  foreign_key = join_keys.foreign_key

  value = transform_value(owner[foreign_key])
  scope = apply_scope(scope, table, key, value)

  if reflection.type
    polymorphic_type = transform_value(owner.class.base_class.name)
    scope = scope.where(table.name => { reflection.type => polymorphic_type })
  end

  scope
end

#next_chain_scope(scope, table, reflection, association_klass, foreign_table, next_reflection) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/pluck_map/association_scope.rb', line 67

def next_chain_scope(scope, table, reflection, association_klass, foreign_table, next_reflection)
  join_keys = reflection.join_keys(association_klass)
  key = join_keys.key
  foreign_key = join_keys.foreign_key

  constraint = table[key].eq(foreign_table[foreign_key])

  if reflection.type
    value = transform_value(next_reflection.klass.base_class.name)
    scope = apply_scope(scope, table, reflection.type, value)
  end

  scope = scope.joins(join(foreign_table, constraint))
end