2017-06-13 87 views
0

我只是想重新啓動那個question。我有同樣的問題有類似的控制器:RoR - 方法'admin?'爲零:NilClass

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 

由於某種原因,在錯誤未定義的方法取得了「管理?」對於零: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 

末 無論如何,我已經切換到德魯的解決方案,它的工作原理,但現在我想知道是什麼問題在第一名?爲什麼它在我的代碼的另一部分中工作,在這個特定的代碼中它不工作?

在此先感謝!

回答

3

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

它會評估!logged_in? || logged_in?第一(總是如此),然後!current_user.admin?,所以它總是會檢查!current_user.admin?,但current_user將爲零時...

未登錄用戶我想你想if !logged_in? || (logged_in? and !current_user.admin?)

,但你可以用unless而不是if重寫(更易讀我認爲?)

除非current_user & & current_user.admin?

+0

太棒了!謝謝!!!知道了...很簡單...再次感謝! – Ardzii

相關問題