From b347c7b78cc8db346a5b5aa4345b4f2a23f5d0e7 Mon Sep 17 00:00:00 2001 From: Chris Gunther Date: Tue, 31 Jan 2012 12:01:48 -0500 Subject: [PATCH] port fix for namespaced params from 2.0 back to 1.6 --- lib/cancan/controller_resource.rb | 15 ++++++++++----- spec/cancan/controller_resource_spec.rb | 12 ++++++++++++ 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/lib/cancan/controller_resource.rb b/lib/cancan/controller_resource.rb index b417d5c..83a77d1 100644 --- a/lib/cancan/controller_resource.rb +++ b/lib/cancan/controller_resource.rb @@ -82,10 +82,7 @@ module CanCan end def build_resource - params = @options[:class] \ - ? @params[@options[:class].to_s.underscore.gsub('/', '_')] \ - : @params[name] || {} - resource = resource_base.new(params) + resource = resource_base.new(resource_params || {}) resource.send("#{parent_name}=", parent_resource) if @options[:singleton] && parent_resource initial_attributes.each do |attr_name, value| resource.send("#{attr_name}=", value) @@ -95,7 +92,7 @@ module CanCan def initial_attributes current_ability.attributes_for(@params[:action].to_sym, resource_class).delete_if do |key, value| - @params[name] && @params[name].include?(key) + resource_params && resource_params.include?(key) end end @@ -210,6 +207,14 @@ module CanCan @name || name_from_controller end + def resource_params + if @options[:class] + @params[@options[:class].to_s.underscore.gsub('/', '_')] + else + @params[namespaced_name.to_s.underscore.gsub("/", "_")] + end + end + def namespaced_name @name || @params[:controller].sub("Controller", "").singularize.camelize.constantize rescue NameError diff --git a/spec/cancan/controller_resource_spec.rb b/spec/cancan/controller_resource_spec.rb index c89480c..eb79324 100644 --- a/spec/cancan/controller_resource_spec.rb +++ b/spec/cancan/controller_resource_spec.rb @@ -47,6 +47,18 @@ describe CanCan::ControllerResource do @controller.instance_variable_get(:@project).should == project end + # Rails includes namespace in params, see issue #349 + it "should create through the namespaced params" do + module MyEngine + class Project < ::Project; end + end + + @params.merge!(:controller => "MyEngine::ProjectsController", :action => "create", :my_engine_project => {:name => "foobar"}) + resource = CanCan::ControllerResource.new(@controller) + resource.load_resource + @controller.instance_variable_get(:@project).name.should == "foobar" + end + it "should properly load resource for namespaced controller when using '::' for namespace" do project = Project.create! @params.merge!(:controller => "Admin::ProjectsController", :action => "show", :id => project.id)