Class: Ransack::Adapters::ActiveRecord::Context

Inherits:
Context
  • Object
show all
Defined in:
lib/ransack/adapters/active_record/context.rb,
lib/ransack/adapters/active_record/3.0/context.rb,
lib/ransack/adapters/active_record/3.1/context.rb,
lib/ransack/adapters/active_record/3.2/context.rb

Constant Summary collapse

JoinDependency =
::ActiveRecord::Associations::ClassMethods::JoinDependency

Instance Attribute Summary

Attributes inherited from Context

#arel_visitor, #auth_object, #base, #engine, #klass, #object, #search, #search_key

Instance Method Summary collapse

Methods inherited from Context

#association_path, #bind, #chain_scope, #contextualize, for, for_class, for_object, #ransackable_alias, #ransackable_association?, #ransackable_attribute?, #ransackable_scope?, #scope_arity, #searchable_associations, #searchable_attributes, #sortable_attributes, #traverse, #unpolymorphize_association

Constructor Details

#initialize(object, options = {}) ⇒ Context

Redefine a few things for ActiveRecord 3.2.



18
19
20
21
# File 'lib/ransack/adapters/active_record/3.0/context.rb', line 18

def initialize(object, options = {})
  super
  @arel_visitor = @engine.connection.visitor
end

Instance Method Details

#alias_trackerObject

Raises:

  • (NotImplementedError)


137
138
139
# File 'lib/ransack/adapters/active_record/context.rb', line 137

def alias_tracker
  @join_dependency.alias_tracker
end

#attribute_method?(str, klass = @klass) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/ransack/adapters/active_record/context.rb', line 44

def attribute_method?(str, klass = @klass)
  exists = false
  if ransackable_attribute?(str, klass)
    exists = true
  elsif (segments = str.split(/_/)).size > 1
    remainder = []
    found_assoc = nil
    while !found_assoc && remainder.unshift(segments.pop) &&
    segments.size > 0 do
      assoc, poly_class = unpolymorphize_association(
        segments.join(Constants::UNDERSCORE)
        )
      if found_assoc = get_association(assoc, klass)
        exists = attribute_method?(
          remainder.join(Constants::UNDERSCORE),
          poly_class || found_assoc.klass
          )
      end
    end
  end
  exists
end

#build_correlated_subquery(association) ⇒ Object

Build an Arel subquery that selects keys for the top query, drawn from the first join association’s foreign_key.

Example: for an Article that has_and_belongs_to_many Tags

context = Article.search.context
attribute = Attribute.new(context, "tags_name").tap do |a|
  context.bind(a, a.name)
end
context.build_correlated_subquery(attribute.parent).to_sql

# SELECT "articles_tags"."article_id" FROM "articles_tags"
# INNER JOIN "tags" ON "tags"."id" = "articles_tags"."tag_id"
# WHERE "articles_tags"."article_id" = "articles"."id"

The WHERE condition on this query makes it invalid by itself, because it is correlated to the primary key on the outer query.



181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/ransack/adapters/active_record/context.rb', line 181

def build_correlated_subquery(association)
  join_constraints = extract_joins(association)
  join_root = join_constraints.shift
  join_table = join_root.left
  correlated_key = join_root.right.expr.left
  subquery = Arel::SelectManager.new(association.base_klass)
  subquery.from(join_root.left)
  subquery.project(correlated_key)
  join_constraints.each do |j|
    subquery.join_sources << Arel::Nodes::InnerJoin.new(j.left, j.right)
  end
  subquery.where(correlated_key.eq(primary_key))
end

#evaluate(search, opts = {}) ⇒ Object



35
36
37
38
39
40
41
42
# File 'lib/ransack/adapters/active_record/context.rb', line 35

def evaluate(search, opts = {})
  viz = Visitor.new
  relation = @object.where(viz.accept(search.base))
  if search.sorts.any?
    relation = relation.except(:order).reorder(viz.accept(search.sorts))
  end
  opts[:distinct] ? relation.distinct : relation
end

#join_associationsObject

All dependent JoinAssociation items used in the search query



122
123
124
125
# File 'lib/ransack/adapters/active_record/context.rb', line 122

def join_associations
  raise NotImplementedError,
  "ActiveRecord 4.1 and later does not use join_associations. Use join_sources."
end

#join_sourcesObject

All dependent Arel::Join nodes used in the search query

This could otherwise be done as ‘@object.arel.join_sources`, except that ActiveRecord’s build_joins sets up its own JoinDependency. This extracts what we need to access the joins using our existing JoinDependency to track table aliases.



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/ransack/adapters/active_record/context.rb', line 97

def join_sources
  base, joins =
  if ::ActiveRecord::VERSION::MAJOR >= 5
    [
      Arel::SelectManager.new(@object.table),
      @join_dependency.join_constraints(@object.joins_values, @join_type)
    ]
  else
    [
      Arel::SelectManager.new(@object.engine, @object.table),
      @join_dependency.join_constraints(@object.joins_values)
    ]
  end
  joins.each do |aliased_join|
    base.from(aliased_join)
  end
  base.join_sources
end

#klassify(obj) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
# File 'lib/ransack/adapters/active_record/context.rb', line 71

def klassify(obj)
  if Class === obj && ::ActiveRecord::Base > obj
    obj
  elsif obj.respond_to? :klass
    obj.klass
  elsif obj.respond_to? :base_klass
    obj.base_klass
  else
    raise ArgumentError, "Don't know how to klassify #{obj}"
  end
end

#lock_association(association) ⇒ Object



141
142
143
# File 'lib/ransack/adapters/active_record/context.rb', line 141

def lock_association(association)
  @lock_associations << association
end

#primary_keyObject



195
196
197
# File 'lib/ransack/adapters/active_record/context.rb', line 195

def primary_key
  @object.table[@object.primary_key]
end

#relation_for(object) ⇒ Object



20
21
22
# File 'lib/ransack/adapters/active_record/context.rb', line 20

def relation_for(object)
  object.all
end

#remove_association(association) ⇒ Object



146
147
148
149
150
151
152
153
154
# File 'lib/ransack/adapters/active_record/context.rb', line 146

def remove_association(association)
  return if @lock_associations.include?(association)
  @join_dependency.join_root.children.delete_if { |stashed|
    stashed.eql?(association)
  }
  @object.joins_values.delete_if { |jd|
    jd.join_root.children.map(&:object_id) == [association.object_id]
  }
end

#table_for(parent) ⇒ Object



67
68
69
# File 'lib/ransack/adapters/active_record/context.rb', line 67

def table_for(parent)
  parent.table
end

#type_for(attr) ⇒ Object



24
25
26
27
28
29
30
31
32
33
# File 'lib/ransack/adapters/active_record/context.rb', line 24

def type_for(attr)
  return nil unless attr && attr.valid?
  name         = attr.arel_attribute.name.to_s
  table        = attr.arel_attribute.relation.table_name
  schema_cache = @engine.connection.schema_cache
  unless schema_cache.send(database_table_exists?, table)
    raise "No table named #{table} exists."
  end
  schema_cache.columns_hash(table)[name].type
end