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

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

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, #bind_pair_for, #chain_scope, #contextualize, for, for_class, for_object, #initialize, #ransackable_alias, #ransackable_association?, #ransackable_attribute?, #ransackable_scope?, #ransackable_scope_skip_sanitize_args?, #scope_arity, #searchable_associations, #searchable_attributes, #sortable_attributes, #traverse, #unpolymorphize_association

Constructor Details

This class inherits a constructor from Ransack::Context

Instance Method Details

#alias_trackerObject



126
127
128
# File 'lib/ransack/adapters/active_record/context.rb', line 126

def alias_tracker
  @join_dependency.send(:alias_tracker)
end

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

Returns:

  • (Boolean)


64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/ransack/adapters/active_record/context.rb', line 64

def attribute_method?(str, klass = @klass)
  exists = false
  if ransackable_attribute?(str, klass)
    exists = true
  elsif (segments = str.split(Constants::UNDERSCORE)).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.



163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/ransack/adapters/active_record/context.rb', line 163

def build_correlated_subquery(association)
  join_constraints = extract_joins(association)
  join_root = join_constraints.shift
  correlated_key = extract_correlated_key(join_root)
  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



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/ransack/adapters/active_record/context.rb', line 24

def evaluate(search, opts = {})
  viz = Visitor.new
  relation = @object.where(viz.accept(search.base))

  if search.sorts.any?
    relation = relation.except(:order)
    # Rather than applying all of the search's sorts in one fell swoop,
    # as the original implementation does, we apply one at a time.
    #
    # If the sort (returned by the Visitor above) is a symbol, we know
    # that it represents a scope on the model and we can apply that
    # scope.
    #
    # Otherwise, we fall back to the applying the sort with the "order"
    # method as the original implementation did. Actually the original
    # implementation used "reorder," which was overkill since we already
    # have a clean slate after "relation.except(:order)" above.
    viz.accept(search.sorts).each do |scope_or_sort|
      if scope_or_sort.is_a?(Symbol)
        relation = relation.send(scope_or_sort)
      else
        case Ransack.options[:postgres_fields_sort_option]
        when :nulls_first
          scope_or_sort = scope_or_sort.direction == :asc ? Arel.sql("#{scope_or_sort.to_sql} NULLS FIRST") : Arel.sql("#{scope_or_sort.to_sql} NULLS LAST")
        when :nulls_last
          scope_or_sort = scope_or_sort.direction == :asc ? Arel.sql("#{scope_or_sort.to_sql} NULLS LAST") : Arel.sql("#{scope_or_sort.to_sql} NULLS FIRST")
        when :nulls_always_first
          scope_or_sort = Arel.sql("#{scope_or_sort.to_sql} NULLS FIRST")
        when :nulls_always_last
          scope_or_sort = Arel.sql("#{scope_or_sort.to_sql} NULLS LAST")
        end

        relation = relation.order(scope_or_sort)
      end
    end
  end

  opts[:distinct] ? relation.distinct : relation
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.



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/ransack/adapters/active_record/context.rb', line 110

def join_sources
  base, joins = begin
    alias_tracker = ::ActiveRecord::Associations::AliasTracker.create(self.klass.connection, @object.table.name, [])
    constraints   = @join_dependency.join_constraints(@object.joins_values, alias_tracker, @object.references_values)

    [
      Arel::SelectManager.new(@object.table),
      constraints
    ]
  end
  joins.each do |aliased_join|
    base.from(aliased_join)
  end
  base.join_sources
end

#klassify(obj) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
# File 'lib/ransack/adapters/active_record/context.rb', line 91

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



130
131
132
# File 'lib/ransack/adapters/active_record/context.rb', line 130

def lock_association(association)
  @lock_associations << association
end

#primary_keyObject



176
177
178
# File 'lib/ransack/adapters/active_record/context.rb', line 176

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

#relation_for(object) ⇒ Object



9
10
11
# File 'lib/ransack/adapters/active_record/context.rb', line 9

def relation_for(object)
  object.all
end

#remove_association(association) ⇒ Object



134
135
136
137
138
139
140
141
142
143
# File 'lib/ransack/adapters/active_record/context.rb', line 134

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

#table_for(parent) ⇒ Object



87
88
89
# File 'lib/ransack/adapters/active_record/context.rb', line 87

def table_for(parent)
  parent.table
end

#type_for(attr) ⇒ Object



13
14
15
16
17
18
19
20
21
22
# File 'lib/ransack/adapters/active_record/context.rb', line 13

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 = self.klass.connection.schema_cache
  unless schema_cache.send(:data_source_exists?, table)
    raise "No table named #{table} exists."
  end
  attr.klass.columns.find { |column| column.name == name }.type
end