Skip to content

Loading…

Allow custom IDs to be specified when calling load_resource #425

Merged
merged 1 commit into from

3 participants

@skhisma

I ran into a strange case where dealing with nested resource with a :path and :as option specified where i was not getting the usual :nested_resource_id generated with route helpers. Added this simple change to allow an :id_param option to override what ID is used out of the params when finding members.

Went with the :id_param name as it largely just affects the id_param method in ControllerResource.

@ryanb
Owner

Thanks for adding this, I'll look into pulling this in for CanCan 2.

@sethvargo

Is there any way to push this out before 2.0? I'm running into a similar issue :(

@ryanb ryanb merged commit 610d7e3 into ryanb:master
@emiltin emiltin pushed a commit to emiltin/cancan that referenced this pull request
Ben Moss Add docs for id_param option of load_resource
Added in ryanb#425 but lacked documentation
9f7f520
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Jul 20, 2011
  1. @skhisma
Showing with 15 additions and 3 deletions.
  1. +6 −2 lib/cancan/controller_resource.rb
  2. +9 −1 spec/cancan/controller_resource_spec.rb
View
8 lib/cancan/controller_resource.rb
@@ -121,11 +121,15 @@ def authorization_action
end
def id_param
- @params[parent? ? :"#{name}_id" : :id]
+ if @options[:id_param]
+ @params[@options[:id_param]]
+ else
+ @params[parent? ? :"#{name}_id" : :id]
+ end
end
def member_action?
- new_actions.include?(@params[:action].to_sym) || @options[:singleton] || (@params[:id] && !collection_actions.include?(@params[:action].to_sym))
+ new_actions.include?(@params[:action].to_sym) || @options[:singleton] || ( (@params[:id] || @params[@options[:id_param]]) && !collection_actions.include?(@params[:action].to_sym))
end
# Returns the class used for this resource. This can be overriden by the :class option.
View
10 spec/cancan/controller_resource_spec.rb
@@ -327,7 +327,15 @@
lambda { resource.load_and_authorize_resource }.should raise_error(CanCan::AccessDenied)
@controller.instance_variable_get(:@custom_project).should == project
end
-
+
+ it "should load resource using custom ID param" do
+ project = Project.create!
+ @params.merge!(:action => "show", :the_project => project.id)
+ resource = CanCan::ControllerResource.new(@controller, :id_param => :the_project)
+ resource.load_resource
+ @controller.instance_variable_get(:@project).should == project
+ end
+
it "should load resource using custom find_by attribute" do
project = Project.create!(:name => "foo")
@params.merge!(:action => "show", :id => "foo")
Something went wrong with that request. Please try again.