cancan icon indicating copy to clipboard operation
cancan copied to clipboard

load_and_authorize_resource with nested and no nested route

Open souzanato opened this issue 11 years ago • 5 comments

Hello everyone!

So I have this controller with two differents routes. One of it is a nested route and another is direct route. It means I have some parameter on nested route that does not exists on direct route.

I tried to perform the load_and_authorize_resource method with a before_filter, so I can detect the nested params presence but got no success.

So how can I perform this? Any help?

Thanks in advance!

souzanato avatar Sep 10 '13 18:09 souzanato

This would be interesting as I faced the same problem here. Using the load_and_authorize_resource in another before_filter does not work, as it's not a method you can call.

sebastianwr avatar Oct 24 '13 13:10 sebastianwr

Hello,

You can use the shallow option with load_and_authorize_resource. https://github.com/ryanb/cancan/wiki/Nested-Resources#shallow-nesting

gdott9 avatar Oct 24 '13 14:10 gdott9

edit: Ah I'm sorry, mixed up this one with another issue.

Of course, nested resource with shallow routing is the way to go.

sebastianwr avatar Oct 29 '13 13:10 sebastianwr

Hi there : ) I seem to have the same problem. I have this in my controller:

class RoomsController < ApplicationController
  load_and_authorize_resource :hotel
  load_and_authorize_resource through: :hotel, shallow: true   

My routes are "/hotels/:id/rooms" and "rooms/:id". I can access the first route, and the authorization is correct, meaning that the owner of an hotel can't access the rooms of other hotels. However, when I try to access rooms/:id, I get a RecordNotFound error (Couldn't find Hotel with id=). Anyone knows how to solve this? Thanks in advance!!

Edit: Nevermind, @francocatena's CanCan fork resolves this :)

rcosteira79 avatar Jan 08 '14 14:01 rcosteira79

I switched to Pundit and it's much easier to manage nested routes.

e.g. I have a Message model, it's nested under events and under users

dorianmariecom avatar Mar 29 '21 21:03 dorianmariecom