开发者

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:

  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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜