Skip to content

Commit

Permalink
Do not execute the scope condition on class permission checks.
Browse files Browse the repository at this point in the history
@conditions.empty? calls ActiveRecord::Relation#empty? when a scoped condition is provided. ActiveRecord::Relation#empty? will query the database while CanCan only needs to check if conditions are set on the rule.
  • Loading branch information
matt-glover authored and bryanrite committed Jan 27, 2014
1 parent a1ba470 commit d3e4fd7
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/cancan/rule.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def matches_conditions?(action, subject, extra_args)
matches_conditions_hash?(subject)
else
# Don't stop at "cannot" definitions when there are conditions.
@conditions.empty? ? true : @base_behavior
conditions_empty? ? true : @base_behavior
end
end

Expand Down
14 changes: 13 additions & 1 deletion spec/cancan/model_adapters/active_record_adapter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -326,5 +326,17 @@
# adapter.matches_condition?(article1, :name.nlike, "%helo%").should be_true
# adapter.matches_condition?(article1, :name.nlike, "%ello worl%").should be_false
end

it 'should not execute a scope when checking ability on the class' do
relation = Article.where(:secret => true)
@ability.can :read, Article, relation do |article|
article.secret == true
end

# Ensure the ActiveRecord::Relation condition does not trigger a count query
stub(relation).count { fail 'Unexpected scope execution.' }

expect { @ability.can? :read, Article }.not_to raise_error
end
end
end
end

0 comments on commit d3e4fd7

Please sign in to comment.