0
根據the Pundit readmeauthorize
應該返回記錄,但當我打電話時,我得到true
。當與權威人士授權時獲取布爾代替記錄
授權返回傳遞給它的對象,所以你可以像 這條產業鏈是:
控制器:
def show @user = authorize User.find(params[:id]) end
的Gemfile:
gem 'rails', '~> 5.1.1'
gem 'devise', '~> 4.3'
gem 'pundit', '~> 1.1'
我的控制器:
class PostsController < ApplicationController
skip_before_action :authenticate_user!, only: [:show, :index]
before_action :set_post, only: [:show, :edit, :update, :destroy]
def show
# just for debugging purposes
raise "Post is a #{@post.class.name}!" unless @post.is_a? Post
end
def set_post
# this should return an instance of post
@post = authorize Post.find(params[:id])
end
end
政策:
class PostPolicy < ApplicationPolicy
class Scope < Scope
def resolve
scope.all
end
end
def show?
true
end
# ...
end
規格:
require 'rails_helper'
RSpec.describe "Posts", type: :request do
subject { response }
describe "GET /posts/:id" do
let!(:post) { create(:post) }
before { get post_path(post) }
it { should be_successful }
end
end
失敗消息:
4) Posts GET /posts/:id
Failure/Error: raise "Post is a #{@post.class.name}!" unless @post.is_a? Post
RuntimeError:
Post is a TrueClass!
雖然它很簡單的補救這一點:
def set_post
@post = Post.find(params[:id]).tap do |p|
@post = Post.find(params[:id]).tap { |r| authorize r }
end
end
林非常好奇,爲什麼它不工作如自述文件所述。這是一個錯誤還是我錯過了什麼?