【问题标题】:Rails 4: Authorizing Users to View, Edit, and Delete PostsRails 4:授权用户查看、编辑和删除帖子
【发布时间】:2023-03-30 14:56:01
【问题描述】:

我希望任何人(即使是未登录的人)都能查看帖子,但只有帖子的所有者才能编辑或销毁帖子。但是,目前,任何用户都可以编辑或销毁任何帖子。如果我改变了

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

到

def set_pin
  @pin = current_user.pins.find(params[:id])
end

当前用户不能编辑其他用户的帖子,也不能查看。请帮帮我。谢谢。

class PinsController < ApplicationController

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

  before_filter :authenticate_user!, except: [:index]

  # GET /pins
  # GET /pins.json
  def index
    @pins = Pin.all
  end

  # GET /pins/1
  # GET /pins/1.json
  def show
  end

  # GET /pins/new
  def new
    @pin = current_user.pins.new
  end

  # GET /pins/1/edit
  def edit
  end

  # POST /pins
  # POST /pins.json
  def create
    @pin = current_user.pins.new(pin_params)

    respond_to do |format|
      if @pin.save
        format.html { redirect_to @pin, notice: 'Pin was successfully created.' }
        format.json { render action: 'show', status: :created, location: @pin }
      else
        format.html { render action: 'new' }
        format.json { render json: @pin.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /pins/1
  # PATCH/PUT /pins/1.json
  def update
    respond_to do |format|
      if @pin.update(pin_params)
        format.html { redirect_to @pin, notice: 'Pin was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @pin.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /pins/1
  # DELETE /pins/1.json
  def destroy
    @pin.destroy
    respond_to do |format|
      format.html { redirect_to pins_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_pin
      @pin = Pin.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def pin_params
      params.require(:pin).permit(:description)
    end
end

【问题讨论】:

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


    【解决方案1】:

    供编辑和销毁使用

    def set_pin
      @pin = current_user.pins.find(params[:id])
    end
    

    【讨论】:

    • 就像我说的,这适用于编辑和销毁,但“显示”也只适用于帖子的所有者。我希望任何人都能够查看这些帖子。
    • 您可以创建两个单独的函数 set_pin 和 set_pin_self 一个用于显示,一个用于编辑和销毁,并使用 Pin.find(params[:id]) 和 current_user.pins.find(params[:id] ) 或者
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 2013-09-03
    相关资源
    最近更新 更多