From 1ade44221a5e54b7c561499b89794150827dd5d6 Mon Sep 17 00:00:00 2001 From: Ryan Bates Date: Fri, 21 May 2010 15:22:21 -0700 Subject: [PATCH] load parent resources for collection actions such 'index' --- CHANGELOG.rdoc | 2 ++ lib/cancan/resource_authorization.rb | 4 +++- spec/cancan/resource_authorization_spec.rb | 13 ++++++++++++- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.rdoc b/CHANGELOG.rdoc index 38ffc70..3a3c89f 100644 --- a/CHANGELOG.rdoc +++ b/CHANGELOG.rdoc @@ -1,3 +1,5 @@ +* Load nested parent resources on collection actions such as "index" (thanks dohzya) + * Adding :name option to load_and_authorize_resource if it does not match controller - see issue #65 * Fixing issue when using accessible_by with nil can conditions (thanks jrallison) - see issue #66 diff --git a/lib/cancan/resource_authorization.rb b/lib/cancan/resource_authorization.rb index 0b7fcec..aa8f710 100644 --- a/lib/cancan/resource_authorization.rb +++ b/lib/cancan/resource_authorization.rb @@ -20,7 +20,9 @@ module CanCan end def load_resource - unless collection_actions.include? @params[:action].to_sym + if collection_actions.include? @params[:action].to_sym + parent_resource + else if new_actions.include? @params[:action].to_sym resource.build(@params[model_name.to_sym]) elsif @params[:id] diff --git a/spec/cancan/resource_authorization_spec.rb b/spec/cancan/resource_authorization_spec.rb index d561fed..6f50b3a 100644 --- a/spec/cancan/resource_authorization_spec.rb +++ b/spec/cancan/resource_authorization_spec.rb @@ -86,12 +86,23 @@ describe CanCan::ResourceAuthorization do end it "should load nested resource and fetch other resource through the association" do - stub(Person).find(456).stub!.abilities.stub!.find(123) { :some_ability } + person = Object.new + stub(Person).find(456) { person } + stub(person).abilities.stub!.find(123) { :some_ability } authorization = CanCan::ResourceAuthorization.new(@controller, {:controller => "abilities", :action => "show", :id => 123, :person_id => 456}, {:nested => :person}) authorization.load_resource + @controller.instance_variable_get(:@person).should == person @controller.instance_variable_get(:@ability).should == :some_ability end + it "should load nested resource for collection action" do + person = Object.new + stub(Person).find(456) { person } + authorization = CanCan::ResourceAuthorization.new(@controller, {:controller => "abilities", :action => "index", :person_id => 456}, {:nested => :person}) + authorization.load_resource + @controller.instance_variable_get(:@person).should == person + end + it "should load nested resource and build resource through a deep association" do stub(Person).find(456).stub!.behaviors.stub!.find(789).stub!.abilities.stub!.build(nil) { :some_ability } authorization = CanCan::ResourceAuthorization.new(@controller, {:controller => "abilities", :action => "new", :person_id => 456, :behavior_id => 789}, {:nested => [:person, :behavior]})