授权crud ruby​​ on rails

时间:2016-08-10 20:50:47

标签: ruby-on-rails ruby ruby-on-rails-4

我开始使用ruby on rails,我想知道如何防止用户编辑不是的记录,这是我的代码:

class PinsController < ApplicationController
    before_action :find_pin, only: [:show, :edit, :update, :destroy, :upvote]
    before_action :authenticate_user!, except: [:index , :show]
    def index
        @pins = Pin.all.order("created_at DESC")
    end

    def show
    end

    def new
        @pin = current_user.pins.build
    end

    def create
        @pin = current_user.pins.build(pin_params)

        if @pin.save
            redirect_to @pin, notice: "Pin creado"
        else
            render 'new'
        end
    end

    def edit
    end

    def update
        if @pin.update(pin_params)
            redirect_to @pin, notice: "Actualizado correctamente"
        else
            render 'edit'
        end
    end

    def destroy
        @pin.destroy
        redirect_to root_path
    end

    def upvote
        @pin.upvote_by current_user
        redirect_to :back
    end

    private

    def pin_params
        params.require(:pin).permit(:title, :description, :image)
    end

    def find_pin
        @pin = Pin.find(params[:id])
    end
end

并且在视图中我有两个按钮,一个用于编辑和删除另一个按钮,因为只有当aparescan是记录的创建者时我才能这样做?

2 个答案:

答案 0 :(得分:2)

before_action :set_user_pins, only: [:edit, :update, :destroy, :show]

def set_user_pins
  @pin = current_user.pins.find_by(id: params[:id])
  redirect_request if @pin.blank?
end

答案 1 :(得分:0)

在您的更新操作中,而不是:if @pin.update(pin_params)

做这样的事情:

pin = current_user&.pins.find_by(id: params[:id])
if pin
  # do the update here because the pin belongs to current_user
else
  # raise a 403 'permission denied' error or something
end

如果您不熟悉安全导航操作符,user&.pinsif !user.nil? then user.pins else nil end相同。

因此,对于2.3之前的ruby versios,您可以pin = current_user.pins.find_by(id: params[:id]) if current_user