Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
How can I use CanCan on a controller without a companion Model? #22
I have a calendar controller which builds and displays a calendar but there is no Calendar model. When I use "load_and_authorize_resource" on the controller it fails with a "uninitialized constant" error. I realize that I probably shouldn't use "load_and_authorize_resource" in this case but I don't really know how to get CanCan to secure the controller otherwise.
Am I missing something simple?
One way around this might be to use the +class+ option on load_and_authorize_resource to point it to another, possibly unrelated, Model. The downside is that you cannot use the surrogate Model for any authentication purposes in the Ability model but in my case (with a Calendar) that's not a big deal.
I ended up using the Ability model itself as the surrogate class and then included a "can :read, Ability" in the user rules. It seems to work OK for what I need. Am I missing something that would open a security hole? Or maybe there is a better way to do what I want?
moite: I don't think I can use the
Darn, this is turning out to be harder than I thought. Maybe I'm coming at the problem wrong...
UPDATE: It turns out that I can use the
I am not sure I completely understand your problem...
You have a
CanCan supports using a symbol instead of a model class when defining permissions. So you can do like this:
And then don't use the
wouldn't be handy in this case to have a symbol you could use - this would ensure authorization at controller level without depending on having an identically named model.
I also met the same problem with "rnhurt", that I want to authorize some controller which doesn't have any corresponding model. e.g.:
I have googled around and checked most of the document, but there's no solution for this. ( elisehuard supplied a solution, however now it's not available in current version 1.4.0)
Finally I come to this workaround: just simply define a blank model for this controller,
and define the ability:
Implementation No.1 that doesn't work:
and I got an exception that is the BEST I had even seen!
so I changed the corresponding code to:
and both of them throws CanCan::AccessDenied exception.
Implementation No.2 that works, I thought about this solution in my dinner time, even before went to bed :-)
windows XP( Linux at home), rails 2.3.5, ruby 1.8.7, cancan 1.4.0