2016-07-17 3 views
0

Я использую devise и имею модель частей в своем веб-приложении Ruby on Rails. Пользователь имеет несколько штук. Прямо сейчас, в контроллере моих объектов, у меня есть метод с именем correct_user, который позволяет только пользователям, которые владеют кусками, редактировать и уничтожать их. Я хочу добавить строку к этому методу, которая позволяет пользователю с идентификатором пользователя 1 из 1 редактировать и уничтожать чьи-либо фрагменты (если current_user.id == 1, а затем разрешать действия edit/destroy). Я пробовал несколько комбинаций, но я продолжаю получать ошибки.Специальный доступ к редактированию моделей Model Devise ID пользователя 1

Вот мой контроллер частей: (метод correct_user это ближе к концу)

class PiecesController < ApplicationController 
    before_action :set_piece, only: [:show, :edit, :update, :destroy] 
    before_action :correct_user, only: [:edit, :update, :destroy] 
    before_action :authenticate_user!, except: [:index, :show] 
    respond_to :html 

    def index 
    @pieces = Piece.all 
    respond_with(@pieces) 
    end 

    def show 
    respond_with(@piece) 
    end 

    def new 
    @piece = current_user.pieces.build 
    respond_with(@piece) 
    end 

    def edit 
    end 

    def create 
    @piece = current_user.pieces.build(piece_params) 
    flash[:notice] = 'Piece was successfully created.' if @piece.save 
    respond_with(@piece) 
    end 

    def update 
    flash[:notice] = 'Piece was successfully updated.' if @piece.update(piece_params) 
    respond_with(@piece) 
    end 

    def destroy 
    flash[:notice] = 'Piece was successfully deleted.' if @piece.destroy 
    respond_with(@piece) 
    end 

    private 
    def set_piece 
     @piece = Piece.find(params[:id]) 
    end 

    def correct_user 
     @piece = current_user.pieces.find_by(id: params[:id]) 
     redirect_to pieces_path, notice: "Access Denied! Not authorized to edit this piece." if @piece.nil? 
    end 

    def piece_params 
     params.require(:piece).permit(:title, :image, :genre, :size, :price, :description, :status) 
    end 
end 

Спасибо, ребята!

ответ

0

В correct_user, изменить зависимость от redirect_to к and return if @piece.nil? and current_user.id != 1, а затем добавить новую строку ниже, что: @piece = Piece.find(params[:id]) if current_user.id == 1, который будет работать только если redirect_to ... and return нет.

(Кроме того, у вас есть current_user.pieces.find_by(id: ...), который может быть просто .find(...) для простоты.)

Смежные вопросы