我如何通过 CanCan 进行授权?
我的控制器中有一个如下所示的方法:
def some_request
user = User.find(params[:friend_user_id])
req = user.requests.build(:from_id => current_user.id)
# do more stuff!
end
出于参数考虑,现在该方法位于名为 RandomController
的控制器中。这既是一个具有非 RESTful 方法的 RESTful 控制器,如下所示。我只使用 authorize_resource
并且没有加载资源。我认为我可以通过在我的能力课程中执行以下操作来管理此问题:
class Ability
include CanCan::Ability
def initialize(user)
if user
can :manage, Request do |req|
req.user_id == user.id
end
end
end
这没有做到。如何修改 some_request 以授权创建请求?基本上我想要执行以下操作:允许任何经过身份验证的用户对属于他们且仅属于他们的请求执行所有 CRUD 操作(:管理)。用户与请求之间存在 has_many
关系,如下所示:
has_many :requests
想法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有几件事:
req.user.id
,它可能不会加载用户资源(而且可能也不应该加载!)。将其更改为req.user_id
并保存用户资源的请求。current_user
对象,而不仅仅是user
。Ryan Bates 在记录 CanCan 的特性和功能方面做得非常出色。查看 RailsCast #192 剧集(或 纯文本 ASCII 转换版本)和 GitHub 项目 了解更多详细信息。
Couple of things:
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.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.