diff --git a/lib/cancan/controller_additions.rb b/lib/cancan/controller_additions.rb index 2dea04c..6c8caa4 100644 --- a/lib/cancan/controller_additions.rb +++ b/lib/cancan/controller_additions.rb @@ -17,10 +17,12 @@ module CanCan end def load_resource # TODO this could use some refactoring - if params[:id] - instance_variable_set("@#{params[:controller].singularize}", params[:controller].singularize.camelcase.constantize.find(params[:id])) - elsif params[params[:controller].singularize.to_sym] - instance_variable_set("@#{params[:controller].singularize}", params[:controller].singularize.camelcase.constantize.new(params[params[:controller].singularize.to_sym])) + unless params[:action] == "index" + if params[:id] + instance_variable_set("@#{params[:controller].singularize}", params[:controller].singularize.camelcase.constantize.find(params[:id])) + else + instance_variable_set("@#{params[:controller].singularize}", params[:controller].singularize.camelcase.constantize.new(params[params[:controller].singularize.to_sym])) + end end end diff --git a/spec/cancan/controller_additions_spec.rb b/spec/cancan/controller_additions_spec.rb index d49b14b..38bb582 100644 --- a/spec/cancan/controller_additions_spec.rb +++ b/spec/cancan/controller_additions_spec.rb @@ -44,7 +44,14 @@ describe CanCan::ControllerAdditions do @controller.instance_variable_get(:@ability).should == :some_resource end - it "should not build a resource of neither id nor attributes are specified" do + it "should build a new resource even if attribute hash isn't specified" do + stub(@controller).params { {:controller => "abilities", :action => "new"} } + stub(Ability).new(nil) { :some_resource } + @controller.load_resource + @controller.instance_variable_get(:@ability).should == :some_resource + end + + it "should not build a resource when on index action" do stub(@controller).params { {:controller => "abilities", :action => "index"} } @controller.load_resource @controller.instance_variable_get(:@ability).should be_nil