使用pundit和Rails 5时“无法找到策略”

时间:2017-08-29 20:02:28

标签: ruby-on-rails ruby-on-rails-5 pundit

我正在使用Rails 5并希望使用pundit来授权我的对象。我已将gem添加到我的Gemfile中并将其放在我的application_controller.rb文件中

class ApplicationController < ActionController::Base

  # Needed for proper authorization
  include Pundit

我在这里创建了一个应用程序策略文件 - app / policies / application_policy.rb

class ApplicationPolicy
  attr_reader :user, :record

  def initialize(user, record)
    @user = user
    @record = record
  end

  def index?
    false
  end

  def show?
    scope.where(:id => record.id).exists?
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    @record.user == @user
  end

  def edit?
    update?
  end

  def destroy?
    @record.user == @user
  end

然后我有一个空白的MyEventPolicy文件(app / policies / my_event_policy.rb)

class MyEventPolicy < ApplicationPolicy
end

然后在我的app / controllers / my_event_controller.rb文件中,我有

  def edit
    @my_event = MyEvent.find(params[:id]) 
    authorize @my_event

但是当我调用上述内容时,我在“授权”行抱怨

时收到错误
unable to find policy `MyEventPolicy` for `#<MyEvent id: 1, ...

我的设置中还缺少什么才能使其正常工作?

编辑:以下是我的app / models / user.rb文件中的内容......

class User < ActiveRecord::Base
  has_many :assignments
  has_many :roles, through: :assignments

  def role?(role)
    roles.any? { |r| r.name.underscore.to_sym == role.to_s.underscore.to_sym }
  end

  def admin?
    role? "Admin"
  end

  def name
    name = first_name
    if !first_name.nil?
      name = "#{name} "
    end
    "#{name}#{last_name}"
  end

  def self.from_omniauth(auth)
    puts "auth id: #{auth.uid} provider: #{auth.provider}"
    user = find_or_create_by(uid: auth.uid, provider: auth.provider)
    user.provider = auth.provider
    user.uid = auth.uid
    user.email = auth.info.email
    user.first_name = auth.info.first_name
    user.last_name = auth.info.last_name
    user.oauth_token = auth.credentials.token
    user.oauth_expires = auth.credentials.expires_at.nil? ? nil : Time.at(auth.credentials.expires_at)
    user.save!
    user
  end

end

0 个答案:

没有答案