特殊访问编辑片段模型设计用户ID 1

时间:2016-07-17 00:55:49

标签: ruby-on-rails ruby

我正在使用设计,并在我的Ruby on Rails网络应用程序中拥有一个模型。用户拥有多件作品。现在,在我的棋子控制器中,我有一个名为correct_user的方法,它只允许拥有这些碎片的用户编辑和销毁它们。我想在这个方法中添加一行,它允许设计用户id为1的用户能够编辑和销毁其他人的部分(如果current_user.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

谢谢你们!

1 个答案:

答案 0 :(得分: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(...)。)