Gemfile
gem 'pundit', '~> 0.2.1'
приложение/контроллеры/application_controller.rb
class ApplicationController < ActionController::Base
include Pundit
...
приложение/политика/application_policy.rb
class ApplicationPolicy < Struct.new(:user, :record)
def index? ; false; end
def show? ; scope.where(id: record.id).exists?; end
def create? ; false; end
def new? ; create?; end
def update? ; false; end
def edit? ; update?; end
def destroy?; false; end
def scope
Pundit.policy_scope!(user, record.class)
end
end
приложение/политика/book_policy.rb
class BookPolicy < ApplicationPolicy
def create?
record.new_record?
end
def new?
create? end
def show?
record.published? || user == record.user || user.is?(:admin)
end
end
приложение/контроллеры/books_controller.rb
class BooksController < ApplicationController
before_action :set_book, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:show]
after_action :verify_authorized, except: :index
after_action :verify_policy_scoped, only: :index
# GET /books/1
def show
authorize(@book)
end
# GET /books/new
def new
@book = Book.new
authorize(@book)
end
# POST /books
def create
@book = current_user.books.build(book_params)
authorize(@book)
if @book.save
redirect_to @book, notice: 'Your book was successfully created.'
else
render action: 'new'
end
end
private
def set_book
@book = Book.find(params[:id])
end
def book_params
params.require(:book).permit(:title, :description)
end
end
<сильные > тест/фабрики/factories.rb
FactoryGirl.define do
factory :user do
sequence(:email) { |n| "email#{n}@x.com" }
password '12345678'
password_confirmation '12345678'
end
factory :book do
title 'xx'
user
end
end