ruby-on-rails - 如何过滤 Rails 中的对象,以便只有创建它的用户或管理员才能销毁该对象?

标签 ruby-on-rails ruby crud before-filter

我有一个简单的 Rails 应用程序,用户可以在其中创建引用(例如,“两件事是无限的:宇宙和人类的愚蠢;我不确定宇宙。”——阿尔伯特·爱因斯坦等)。

我希望只有创建报价的用户或管理员能够编辑和删除报价。

目前我有一个之前的过滤器,它设置了创建引号的用户,如下所示:

before_action :correct_user, only: :destroy

这是我的 Quotes controller :

class QuotesController < ApplicationController
  before_action :set_artist,   only: [:show, :edit, :update, :destroy]
  before_action :logged_in_user, only: [:create, :new, :destroy, :update, :edit ]
  before_action :correct_user,   only: :destroy

  def index
    @quotes = Quote.all.paginate(page: params[:page], per_page: 12)
  end

  def show
  end

  def new
    @quote = Quote.new
  end

  def create
    @quote = current_user.quotes.build(quote_params)
    if @quote.save
      flash[:success] = "Quote created!"
      redirect_to @quote
    else
      render :new
    end
  end

  def edit
  end

  def update
    if @quote.update(quote_params)
      flash[:success] = "Quote updated"
      redirect_to @quote
    else
      render :edit
    end
  end

  def destroy
    @quote.destroy
    flash[:success] = "Quote deleted"
    redirect_back(fallback_location: browse_path)
  end

  private

    def set_artist
      @quote = Quote.find(params[:id])
    end

    def quote_params
      params.require(:quote).permit(:content, :source, :topic_id, :speaker_id)
    end

    def correct_user
      @quote = current_user.quotes.find_by(id: params[:id])
      redirect_to root_url if @quote.nil?
    end
end

在 Rails 中执行此操作的惯用正确方法是什么?我应该这样做吗:

def correct_user
  if user.admin?
    @quote = current_user.quotes.find_by(id: params[:id])
  else
   @quote = current_user.quotes.find_by(id: params[:id])
  end
  redirect_to root_url if @quote.nil?
end

是否有我缺少的更简洁或 Rails 方式来执行此操作?另外,如何确保只有创建报价的用户才能删除或编辑报价?我的 correct_user 方法是否已经涵盖了这一点?

最佳答案

我会在操作前设置两个。

before_action :resource, only: [:edit, :update, :destroy]
before_action :allow_admin, only: [:edit, :update, :destroy]

首先会找到引用资源

def resource
  @quote = current_user.quotes.find_by(id: params[:id])
end

其他将允许管理员访问资源

def allow_admin
  if current_user.admin? && @quote.nil?
    @quote = Quote.find_by(id: params[:id])
    # Search all quotes, as admin has access to all
  elsif @quote.nil?
    redirect_to root_url
  end
end

关于ruby-on-rails - 如何过滤 Rails 中的对象,以便只有创建它的用户或管理员才能销毁该对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48734925/

相关文章:

ruby-on-rails - 从 Rails 3 升级到 Rails 3.1

ruby-on-rails - 仅具有查询字符串或数字的 Rails 4 路由约束

ruby-on-rails - Rails 4 + react rails gem : Could not find generator 'react:install'

ruby-on-rails - Rails3 使用 Iframe 进行 ajax 上传

ruby-on-rails - 测试时,每次在 Rails 3.2 中调整 Javascript 文件时都必须预编译 Assets 吗?

ruby - [square brackets] 在 Ruby 中有哪些不同用途?

ruby-on-rails - 如何在开发环境中的 rails 中预编译 Assets ?

java - 如何在全局变量的回调中存储数据?

WCF SOA : CRUD Data Access Service. ..为什么要麻烦(或者我们的设计错误)?

c - 使用 ANSI 函数获取文本文件的特定行