1

我正在尝试使用 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

      ...

模型/能力.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
4

1 回答 1

1

尝试这个

load_and_authorize_resource :character, parent: false

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

于 2015-05-06T15:44:37.250 回答