Skip to content

Commit

Permalink
Merge pull request ryanb#632 from andhapp/fix-issue-327
Browse files Browse the repository at this point in the history
Fix to handle MetaWhere and non-MetaWhere conditions correctly.
  • Loading branch information
ryanb committed May 29, 2012
2 parents b3f9ffe + c27ead5 commit 80a8c39
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/cancan/model_adapters/active_record_adapter.rb
Expand Up @@ -89,7 +89,12 @@ def database_records
if override_scope
@model_class.scoped.merge(override_scope)
elsif @model_class.respond_to?(:where) && @model_class.respond_to?(:joins)
@model_class.where(conditions).joins(joins)
mergeable_conditions = @rules.select {|rule| rule.unmergeable? }.blank?
if mergeable_conditions
@model_class.where(conditions).joins(joins)
else
@model_class.where(*(@rules.map(&:conditions))).joins(joins)
end
else
@model_class.scoped(:conditions => conditions, :joins => joins)
end
Expand Down
4 changes: 4 additions & 0 deletions lib/cancan/rule.rb
Expand Up @@ -54,6 +54,10 @@ def conditions_empty?
@conditions == {} || @conditions.nil?
end

def unmergeable?
@conditions.respond_to?(:keys) && (! @conditions.keys.first.kind_of? Symbol)
end

def associations_hash(conditions = @conditions)
hash = {}
conditions.map do |name, value|
Expand Down
10 changes: 10 additions & 0 deletions spec/cancan/model_adapters/active_record_adapter_spec.rb
Expand Up @@ -236,6 +236,16 @@
@ability.should_not be_able_to(:read, article2)
end

it "should merge MetaWhere and non-MetaWhere conditions" do
@ability.can :read, Article, :priority.lt => 2
@ability.can :read, Article, :priority => 1
article1 = Article.create!(:priority => 1)
article2 = Article.create!(:priority => 3)
Article.accessible_by(@ability).should == [article1]
@ability.should be_able_to(:read, article1)
@ability.should_not be_able_to(:read, article2)
end

it "should match any MetaWhere condition" do
adapter = CanCan::ModelAdapters::ActiveRecordAdapter
article1 = Article.new(:priority => 1, :name => "Hello World")
Expand Down
7 changes: 7 additions & 0 deletions spec/cancan/rule_spec.rb
Expand Up @@ -36,4 +36,11 @@
rule = CanCan::Rule.new(true, :read, Integer, nil, nil)
rule.associations_hash.should == {}
end

it "should not be mergeable if conditions are not simple hashes" do
meta_where = OpenStruct.new(:name => 'metawhere', :column => 'test')
@conditions[meta_where] = :bar

@rule.should be_unmergeable
end
end

0 comments on commit 80a8c39

Please sign in to comment.