load_and_authorize_resource null cancancan

时间:2014-12-09 15:43:21

标签: ruby-on-rails cancancan

我尝试使用cancancan加载资源,但它一直返回null,我不知道为什么。 有人可以指出我的错误吗?我试图在rails控制台中进行一些调试,以确保关联条件在某些情况下会返回true,在我的测试用例中,所有字符(2)都属于用户。

 Character.all.each {|char| puts user.characters.include? char }
  Character Load (0.3ms)  SELECT "characters".* FROM "characters"
true
true

这是代码

API / V1 / characters_controller.rb

module Api
  module V1
    class CharactersController < ApplicationController
      load_and_authorize_resource

      def index
        render json: @characters
      end

      ...

模型/ ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    # Define abilities for the passed in user here. For example:
    #
    user ||= User.new # guest user (not logged in)
    can :create, User

    if User.exists?(user)
      can :create, ApiKey
      can [:read, :destroy], Character do |character|
        user.characters.include? character
      end
    end
  end
end

响应

HTTP/1.1 200 OK 
X-Frame-Options: SAMEORIGIN
X-Xss-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Content-Type: application/json; charset=utf-8
Etag: "37a6259cc0c1dae299a7866489dff0bd"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: f7102bb1-1928-4ef4-a459-2e9d62c5cdaf
X-Runtime: 5.110437
Server: WEBrick/1.3.1 (Ruby/2.1.2/2014-05-08)
Date: Tue, 09 Dec 2014 15:28:18 GMT
Content-Length: 4
Connection: close

null

1 个答案:

答案 0 :(得分:1)

试试这个

load_and_authorize_resource :character, parent: false

您可以在此处阅读详情http://www.rubydoc.info/github/CanCanCommunity/cancancan/CanCan/ControllerAdditions/ClassMethods:load_resource