如何同时允许:correct_user和:admin_user删除before_action的帖子?

时间:2015-01-26 01:26:57

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

更新后跟答案,但rails告诉我

未定义的方法`destroy'为nil:NilClass

我认为correct_user方法和admin_user方法都需要重写,这里使用的逻辑Harts非常奇怪

class MicropostsController < ApplicationController
  before_action :logged_in_user, only: [:create, :destroy]
  before_action :correct_user_or_admin_user, only: :destroy

  def destroy
    @micropost.destroy
    flash[:success] = "Micropost deleted"
    redirect_to request.referrer || root_url
  end

  private

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

    def admin_user
      #i dont know how to write it
    end

    def correct_user_or_admin_user
      correct_user || admin_user
    end

1 个答案:

答案 0 :(得分:1)

这样做是不可能的,因为:corrent_user:admin_user只是before_action方法的符号参数。

你能做的是:

before_action :load_micropost,  only: :destroy
before_action :admin_or_author, only: :destroy

在控制器中使用以下方法:

private
def load_micropost
  # renders 404 on production if not found
  @micropost = Micropost.find(params[:id])
end

def admin_or_author
  redirect_to(root_url) unless administrator? || authorship?
end

def administrator?
  current_user.admin?
end

def authorship?
  @micropost.user == current_user
end