Class: CanCan::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/cancan/query.rb

Overview

Generates the sql conditions and association joins for use in ActiveRecord queries. Normally you will not use this class directly, but instead through ActiveRecordAdditions#accessible_by.

Instance Method Summary collapse

Constructor Details

#initialize(sanitizer, can_definitions) ⇒ Query

Returns a new instance of Query.



6
7
8
9
# File 'lib/cancan/query.rb', line 6

def initialize(sanitizer, can_definitions)
  @sanitizer = sanitizer
  @can_definitions = can_definitions
end

Instance Method Details

#conditionsObject

Returns conditions intended to be used inside a database query. Normally you will not call this method directly, but instead go through ActiveRecordAdditions#accessible_by.

If there is only one “can” definition, a hash of conditions will be returned matching the one defined.

can :manage, User, :id => 1
query(:manage, User).conditions # => { :id => 1 }

If there are multiple “can” definitions, a SQL string will be returned to handle complex cases.

can :manage, User, :id => 1
can :manage, User, :manager_id => 1
cannot :manage, User, :self_managed => true
query(:manage, User).conditions # => "not (self_managed = 't') AND ((manager_id = 1) OR (id = 1))"


26
27
28
29
30
31
32
33
34
35
# File 'lib/cancan/query.rb', line 26

def conditions
  if @can_definitions.size == 1 && @can_definitions.first.base_behavior
    # Return the conditions directly if there's just one definition
    @can_definitions.first.tableized_conditions
  else
    @can_definitions.reverse.inject(false_sql) do |sql, can_definition|
      merge_conditions(sql, can_definition.tableized_conditions, can_definition.base_behavior)
    end
  end
end

#joinsObject

Returns the associations used in conditions for the :joins option of a search. See ActiveRecordAdditions#accessible_by for use in Active Record.



39
40
41
42
43
44
45
# File 'lib/cancan/query.rb', line 39

def joins
  joins_hash = {}
  @can_definitions.each do |can_definition|
    merge_joins(joins_hash, can_definition.associations_hash)
  end
  clean_joins(joins_hash) unless joins_hash.empty?
end