我如何通过 CanCan 进行授权?

发布于 2024-12-01 15:28:48 字数 768 浏览 2 评论 0原文

我的控制器中有一个如下所示的方法:

 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

九歌凝 2024-12-08 15:28:48

有几件事:

  1. 您正在调用 req.user.id,它可能不会加载用户资源(而且可能也不应该加载!)。将其更改为 req.user_id 并保存用户资源的请求。
  2. CanCan 要求您使用 current_user 对象,而不仅仅是 user

Ryan Bates 在记录 CanCan 的特性和功能方面做得非常出色。查看 RailsCast #192 剧集(或 纯文本 ASCII 转换版本)和 GitHub 项目 了解更多详细信息。

Couple of things:

  1. you're calling req.user.id, which may not be loading the user resource (and probably shouldn't, either!). Change that to req.user_id and save yourself the request of the user resource.
  2. CanCan requires you use the current_user object, not just user.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文