RoR - 方法'管理员?'为零:NilClass

时间:2017-06-13 13:59:49

标签: ruby-on-rails methods undefined

我只是想重新启动question。我对类似的控制器也有同样的问题:

    class CategoriesController < ApplicationController

  before_action :require_admin, except: [:index, :show]

  def index
    @categories = Category.paginate(page: params[:page], per_page: 5)
  end

  def new
    @category = Category.new
  end

  def create
    @category = Category.new(category_params)
    if @category.save
      flash[:success] = "La nueva categoria se creó correctamente"
      redirect_to categories_path
    else 
      render 'new'
    end
  end

  def index
     @categories = Category.paginate(page: params[:page], per_page: 5)
  end

  def show
  end

  private

  def category_params
    params.require(:category).permit(:name)
  end

  def require_admin
    if !logged_in? || logged_in? and !current_user.admin?
      flash[:danger] = "Solamente el admin puede acceder a esta seccion"
    redirect_to categories_path
    end
  end


end

由于某些原因导致错误未定义的方法&#39; admin?&#39; for nil:NilClass当我有另一部分完全相同的代码时,工作正常:

    Class ArticlesController < ApplicationController

  before_action :set_article, only: [:edit, :update, :show, :destroy]
  before_action :require_user, only: [:new, :create, :update, :edit, :destroy]
  before_action :require_same_user, only: [:update, :edit, :destroy]

  def index
    @articles = Article.paginate(page: params[:page], per_page: 5)
  end

  def new
    @article = Article.new
  end

  def create
    @article = Article.new(article_params)
    @article.user = current_user
    if @article.save
      flash[:success] = "El articulo fue correctamente creado!"
      redirect_to article_path(@article)
    else
      render 'new'
    end
  end

  def edit
  end

  def update
    if @article.update(article_params)
      flash[:success] = "El articulo fue correctamente actualizado!"
      redirect_to article_path(@article)
    else
      render 'edit'
    end
  end

  def show
  end

  def destroy
    @article.destroy
    flash[:success] = "El articulo fue correctamente borrado!"
    redirect_to articles_path
  end

  private
    def set_article
      @article = Article.find(params[:id])
    end

    def article_params
      params.require(:article).permit(:title, :description)
    end

    def require_same_user
      if current_user != @article.user and !current_user.admin?
        flash[:danger] = "Solamente puede editar y borrar sus propios articulos"
        redirect_to root_path
      end
    end

端 无论如何,我已经切换到Drew的解决方案,它现在有效,但我想知道问题首先是什么?为什么它在我的代码的另一部分中起作用,在这个特定的部分中它不起作用?

提前致谢!

1 个答案:

答案 0 :(得分:3)

  

if!logged_in? ||登录?和!current_user.admin?

它会首先评估!logged_in? || logged_in?(始终为真)然后评估!current_user.admin?,因此它会始终检查!current_user.admin?,但当用户未登录时current_user将为nil在...

我想你想要if !logged_in? || (logged_in? and !current_user.admin?)

但您可以使用unless而不是if重写它(我认为更具可读性)。

  

除非current_user&amp;&amp; current_user.admin?