From 9a7c4273737b415fa6f7a9c68c11c0754bf134ab Mon Sep 17 00:00:00 2001 From: Nanda Lopes Date: Thu, 4 Nov 2010 02:47:02 +0800 Subject: [PATCH] Fix NoMethodError Raises NoMethodError when using ":singleton => true, :shallow => true" and parent_resource is nil --- lib/cancan/controller_resource.rb | 8 ++++++-- spec/cancan/controller_resource_spec.rb | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/lib/cancan/controller_resource.rb b/lib/cancan/controller_resource.rb index 91878c0..74bf71f 100644 --- a/lib/cancan/controller_resource.rb +++ b/lib/cancan/controller_resource.rb @@ -61,7 +61,11 @@ module CanCan end def build_resource - resource = resource_base.send(@options[:singleton] ? "build_#{name}" : "new") + if @options[:singleton] && resource_base.respond_to?("build_#{name}") + resource = resource_base.send("build_#{name}") + else + resource = resource_base.send("new") + end initial_attributes.each do |name, value| resource.send("#{name}=", value) end @@ -74,7 +78,7 @@ module CanCan end def find_resource - if @options[:singleton] + if @options[:singleton] && resource_base.respond_to?(name) resource_base.send(name) else @options[:find_by] ? resource_base.send("find_by_#{@options[:find_by]}!", id_param) : resource_base.find(id_param) diff --git a/spec/cancan/controller_resource_spec.rb b/spec/cancan/controller_resource_spec.rb index 80e60dc..84998ea 100644 --- a/spec/cancan/controller_resource_spec.rb +++ b/spec/cancan/controller_resource_spec.rb @@ -241,6 +241,21 @@ describe CanCan::ControllerResource do @controller.instance_variable_get(:@project).name.should == "foobar" end + it "should find record through has_one association with :singleton and :shallow options" do + project = Project.create! + @params.merge!(:action => "show", :id => project.id) + resource = CanCan::ControllerResource.new(@controller, :through => :category, :singleton => true, :shallow => true) + resource.load_resource + @controller.instance_variable_get(:@project).should == project + end + + it "should build record through has_one association with :singleton and :shallow options" do + @params.merge!(:action => "create", :project => {:name => "foobar"}) + resource = CanCan::ControllerResource.new(@controller, :through => :category, :singleton => true, :shallow => true) + resource.load_resource + @controller.instance_variable_get(:@project).name.should == "foobar" + end + it "should only authorize :read action on parent resource" do project = Project.create! @params.merge!(:action => "new", :project_id => project.id)