2016-02-03 3 views
1

Я создал веб-приложение с использованием рельсов 4.2.4, разработал и установил штифты, в которых пользователи могут использовать CRUD.pundit for rails problem configuration

Я собираюсь лечить себя, пытаясь заставить pundit работать так, чтобы только администратор мог CRUD нажимать, все пользователи, которые вошли в систему, или гости могут видеть и не могут создавать, обновлять или уничтожать.

Я получаю перечисление ошибок, как это>enter image description here

Факты:

У меня есть 2 модели pin.rb и user.rb

У меня есть pins_controller.rb

I сделал миграцию add_admin_to_users.rb (мне нужно дальнейшее вмешательство в консоль, чтобы установить что-то для администратора помимо этого)

Могу ли я получить помощь с синтаксисом и моего неудавшегося подходом

class ApplicationPolicy 
    attr_reader :user, :pin 

    def initialize(user, pin) 
    raise Pundit::NotAuthorizedError, "must be logged in" unless user 
    @user = user 
    @pin = pin 
    end 

    def index? 
    true 
    end 

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

    def create? 
    user.admin? 
    end 

    def new? 
    user.admin? 
    end 

    def update? 
    user.admin? 
    end 

    def edit? 
    update? 
    end 

    def destroy? 
    user.admin? 
    end 

    def scope 
    Pundit.policy_scope!(user, record.class) 
    end 

    class Scope 
    attr_reader :user, :scope 

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

    def resolve 
     scope 
    end 
    end 
end 

BLOCKQUOTE

class PinsController < ApplicationController 
    before_action :set_pin, only: [:show, :edit, :update, :destroy] 
    before_action :correct_user, only: [:edit, :update, :destroy] 
    before_action :authenticate_user!, except: [:index, :show] 

    def index 
    if params[:search].present? && !params[:search].nil? 
     @pins = Pin.where("description LIKE ?", "%#{params[:search]}%").paginate(:page => params[:page], :per_page => 15) 
    else 
     @pins = Pin.all.order("created_at DESC").paginate(:page => params[:page], :per_page => 15) 
    end 
    end 


    def show 

    end 


    def new 
    @pin = current_user.pins.build 
    end 


    def edit 
    end 


    def create 
    @pin = current_user.pins.build(pin_params) 
    if @pin.save 
     redirect_to @pin, notice: 'Pin was successfully created.' 
    else 
     render :new 
    end 
    end 


    def update 
    if @pin.update(pin_params) 
     redirect_to @pin, notice: 'Pin was successfully updated.' 
    else 
     render :edit 
    end 
    end 


    def destroy 
    @pin.destroy 
    redirect_to pins_url 
    end 


private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_pin 
     @pin = Pin.find_by(id: params[:id]) 
    end 

    def correct_user 
     @pin = current_user.pins.find_by(id: params[:id]) 
     redirect_to pins_path, notice: "Not authorized to edit this pin" if @pin.nil? 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def pin_params 
     params.require(:pin).permit(:description, :image) 
    end 
end 

BLOCKQUOTE

class ApplicationController < ActionController::Base 
include Pundit 
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized 
protect_from_forgery with: :exception 
before_filter :configure_permitted_parameters, if: :devise_controller? 

protected 

def configure_permitted_parameters 
    devise_parameter_sanitizer.for(:sign_up) << :name 
    devise_parameter_sanitizer.for(:account_update) << :name 
end 

private 

def user_not_authorized 
    flash[:warning] = "You are not authorized to perform this action." 
    redirect_to(request.referrer || root_path) 
end 
end 
+2

у вас есть класс 'PinPolicy'? :) –

+2

никогда не слышал об этом, –

+0

Это то, что мне нужно в этом коде –

ответ

2

Ошибка возникает чаще всего просто сделать в факт, что, как говорится в исключении, нет класса PinPolicy. Помимо общего ApplicationPolicy, вы также должны определить политику для каждого ресурса (который наследуется от основного ApplicationPolicy).

Добавить под /policies каталог:

class PinPolicy < ApplicationPolicy 
    class Scope < Scope 
    def resolve 
     return scope if user.admin? 
     fail 'scope is not defined' 
    end 
    end 
end 
+0

Как мне это закодировать в политике приложения, ниже инициализатора def, или что. Нужно ли мне удалять код в моей политике выше –

+0

@ChrisDormani Создайте новый файл в 'app/policies' под названием' pin_policy.rb' и поместите код, который я показал там –

+0

ценю ваше время, попробуем это на мгновение –