簡體   English   中英

限制用戶在博客中創建新文章會給出“未定義的方法“ is_admin?” for nil:NilClass”在Rails應用程序中的ruby中

[英]restricting users to create new article in blog gives “ undefined method `is_admin?' for nil:NilClass” in ruby on rails app

我在ruby on rails上實現博客應用,我想限制普通用戶(只有admin可以創建)才能創建新文章。 為此,我將befor_filter放在后面的articles_controller.rb文件中。 我已經在用戶界面中向用戶隱藏了創建按鈕,但是普通用戶仍然可以通過在瀏覽器的地址欄中鍵入來創建新文章。通過使用以下代碼,普通用戶無法進入新文章頁面,但是當出現以下情況時,它會給我“未定義的方法“ is_admin”?我在地址欄中輸入。有關更多信息,我已經實現了用於用戶認證的裝置。

class ArticlesController < ApplicationController
  before_filter :is_user_admin, only: [:new, :create]

  def is_user_admin
    unless  current_user.is_admin?
      :root 
      return false
    end
  end
end 



class ArticlesController < ApplicationController
  before_filter :is_user_admin, only: [:new, :create]

  def is_user_admin
    unless  current_user.is_admin?
      :root 
      return false
    end
  end

    def index
        @articles = Article.all(:order => "created_at DESC")
    end

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

    def new
      @article = Article.new
    end

    def create
      @article = Article.new(params[:article])
      @article.user_id = current_user.id
      @article.save
      redirect_to article_path(@article)
    end

    def destroy
      @article = Article.find(params[:id])
      @article.destroy
      redirect_to action:  'index'  
    end

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

    def update
      @article = Article.find(params[:id])
      @article.update_attributes(params[:article])
      flash.notice = "Article '#{@article.title}' Updated!"
      redirect_to article_path(@article)
     end
end

applicaiton_controller.rb

class ApplicationController < ActionController::Base
    protect_from_forgery
      def after_sign_in_path_for(user)
         if current_user.is_admin?
             dashboard_index_path
         else
             :root
         end
      end

end

基本上,我想限制普通用戶(非管理員)從UI(完成)或在地址欄中鍵入地址來創建,更新或刪除文章。 我不知道為什么要得到這個,我該怎么做才能避免這種情況。 我應該在application_controller.rb文件中編寫上述方法嗎?

您的current_user顯然為nil。

您應該在控制器頂部放置before_filter :authenticate_user!, :except => [:show, :index]以便對用戶進行身份驗證。

您可能希望將用戶重定向為登錄名,以便他們(如果不是管理員)無法訪問您控制器中的操作。 因此,您可以執行以下操作:

def is_user_admin
  redirect_to(action: :index) unless current_user.try(:is_admin?)
end 

在檢查權限之前,請確保至少有一個用戶。 您可以將以下代碼添加到每個需要身份驗證的控制器中:

 before_filter :authenticate_user!

這樣做,您將始終擁有當前用戶,因此可以按照您指出問題的方式檢查其許可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM