How do I authorize this with CanCan?
I have a method that looks like the following in my controller:
def some_request
user = User.find(params[:friend_user_id])
req = user.requests.build(:from_id => current_user.id)
# do more stuff!
end
Now this is in a controller called RandomController
for arguments sake. This is both a RESTful controller with nonRESTful methods as depicted below. I'm only using authorize_resource
and no loading of resources. I thought I'd be able to manage this by doing the following in my Ability class:
class Ability
include CanCan::Ability
def initialize(user)
if user
can :manage, Request do |req|
req.user_id == user.id
end
end
end
This isn't doing it. How do I modify some_request to authorize the creation of a Request? Basically I want to do the following: Allow any authenticated user to perform all CRUD operations (:manage) on a Request that belongs to them and them only. User has a relationship of has_many
with Request as in:
开发者_运维百科has_many :requests
thoughts?
Couple of things:
- you're calling
req.user.id
, which may not be loading the user resource (and probably shouldn't, either!). Change that toreq.user_id
and save yourself the request of the user resource. - CanCan requires you use the
current_user
object, not justuser
.
Ryan Bates has done a fantastic job of documenting the features and capabilities of CanCan. Have a look at the RailsCast #192 episode (or the plain-text ASCII-cast version) and the GitHub project for more details.
精彩评论