Авторизация по моей проблеме с личным блогом - PullRequest
0 голосов
/ 01 января 2019

У меня проблемы с написанием политик с использованием Pundit в моем личном проекте.

По какой-то причине я получаю ошибку «Авторизация не выполнена», когда я пытаюсь обновить запись в блоге, и не могу создать запись в блоге, не отправив пустую запись.

Вот мой контроллер сообщений:

class PostsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]

after_action :verify_authorized, except: [:index, :show]

def index
 @posts = Post.order(created_at: :desc).page(params[:page]).per(10)
 #authorize @posts
end

def new
 authorize @post
 @post = current_user.posts.build
 if @post.save
  redirect_to @post, notice: 'Post was successfully created.'
 else
  render :new
 end
end

def show
 set_post
end

def edit
 set_post
 authorize @post
end

def update
 set_post
 authorize @post
 @post.update(post_params)
 redirect_to @post
end

def destroy
 set_post
 authorize @post
 @post.destroy

 redirect_to action: "index", notice: "The post was removed"
end

def upvote
    @post.upvote_from current_user
    authorize @post
end

def downvote
    @post.downvote_from current_user
    authorize @post
end



def create
    @post = current_user.posts.build(post_params)
    authorize @post
    respond_to do |format|
        if @post.save
            format.html {redirect_to @post, notice: 'Blog post has been posted!'}
            format.json {render :show, status: :created, location: @post}
        else
            format.html {render :new}
            format.json {render json: @post.errors, status: :unprocessable_entity}
        end
    end

end

private
  def post_params
      params.require(:post).permit(:title, :content, :header_image, uploads: [])
  end

  def set_post
      @post = Post.friendly.find(params[:id])
#    authorize @post
  end

end

Вот и моя политика сообщений.Я не знаю, исходит ли ошибка из политики или из контроллера:

class PostPolicy < ApplicationPolicy
 class Scope < Scope
  def resolve
   scope.where(user_id: @user.try(:id))
  end
 end

 attr_reader :user, :post

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


def show?
 true
end

def index?
 true
end

def create?
 is_contributor_or_admin?
end

def update?
 is_author_of_post_or_admin?
end

def destroy?
 is_author_of_post_or_admin?
end





private

 def user_not_authorized
  flash[:alert] = "Can't let you do that, " + @user.username + "!"
 end

 def is_admin?
  @user.role_id == 1
 end

 def is_contributor_or_admin?
  @user.role_id == 1 || @user.role_id == 2
 end

 def is_author_of_post_or_admin?
  @user.role_id == 1 || @post.user.username == @user.username
 end


end

Я надеюсь, что смогу найти способ создания политик.Если вам потребуется дополнительная информация, такая как код для других файлов, или какие-либо вопросы, касающиеся форматирования, сообщите мне.

...