Module: CanCan::ModelAdapters::ActiveRecordAdapter

Includes:
Joins
Included in:
ActiveRecord4Adapter
Defined in:
lib/cancan/model_adapters/active_record_adapter.rb,
lib/cancan/model_adapters/can_can/model_adapters/active_record_adapter/joins.rb

Defined Under Namespace

Modules: Joins

Instance Method Summary collapse

Methods included from Joins

#joins

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 ModelAdditions#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))"


24
25
26
27
28
29
30
31
32
33
# File 'lib/cancan/model_adapters/active_record_adapter.rb', line 24

def conditions
  compressed_rules = RulesCompressor.new(@rules.reverse).rules_collapsed.reverse
  conditions_extractor = ConditionsExtractor.new(@model_class)
  if compressed_rules.size == 1 && compressed_rules.first.base_behavior
    # Return the conditions directly if there's just one definition
    conditions_extractor.tableize_conditions(compressed_rules.first.conditions).dup
  else
    extract_multiple_conditions(conditions_extractor, compressed_rules)
  end
end

#database_recordsObject



41
42
43
44
45
46
47
48
49
# File 'lib/cancan/model_adapters/active_record_adapter.rb', line 41

def database_records
  if override_scope
    @model_class.where(nil).merge(override_scope)
  elsif @model_class.respond_to?(:where) && @model_class.respond_to?(:joins)
    mergeable_conditions? ? build_relation(conditions) : build_relation(*@rules.map(&:conditions))
  else
    @model_class.all(conditions: conditions, joins: joins)
  end
end

#extract_multiple_conditions(conditions_extractor, rules) ⇒ Object



35
36
37
38
39
# File 'lib/cancan/model_adapters/active_record_adapter.rb', line 35

def extract_multiple_conditions(conditions_extractor, rules)
  rules.reverse.inject(false_sql) do |sql, rule|
    merge_conditions(sql, conditions_extractor.tableize_conditions(rule.conditions).dup, rule.base_behavior)
  end
end