load_resource should try to intelligently load nested resources:
should result in the functional equivalent of the following:
@foo = Foo.find(params[:foo_id])
@bar = @foo.bars.find(params[:id])
This is definitely something which needs to be done, but I'm unsure of the best way to do it. You presented a solution which tries to guess at the nesting, but I wonder if there's too much magic going on.
I would rather the nesting be more explicit in the load_resource before filter. Other libraries have gotten around this by making their own method which takes parameters.
# in controller
load_and_authorize_resource :nested => :foo
This would set up the before filter and handle nesting properly. One could also pass other options here to customize the name of the resource to be loaded, etc.
That said, I'm unsure of how far I really want take CanCan into this area.
I think this would be a great addition. For your example, you could look for a current_foo method to load foo and then make sure that the user has permission to access it.
adding :nested option for load_resource - closed by cd217eb
I have accounts using subdomains. In ApplicationController I am creating a @current_account instance variable with a before_filter using Account.find_by_subdomain!(current_subdomain).
Currently, to use load_and_authorize_resource :nested => :account I must define params[:account_id] = @current_account.id.to_i in ApplicationController as well. However, this results in the same two queries to get the current account. Could we get the option to do something like this to supply the instance?
load_and_authorize_resource :nested => :account
params[:account_id] = @current_account.id.to_i
load_and_authorize_resource :nested => @current_account
That won't work since 'load_and_authorize_resource' is a class level method and @current_account is an instance level variable.
Your best bet is overriding "load_resource" in your ApplicationController to load the account and then call the CanCan load_resource method
Ahh, okay, that makes sense. I'll be doing that then. Thank you for your help and the quick response rmm!