0

在我的应用程序中,我只想允许具有管理员权限的用户访问此模型。所以我设置了 before_filter 来检查用户是否是管理员。这种方法的问题在于,在管理员用户通过过滤器后,他/她将无法重定向到该操作。相反,只有视图被渲染,这导致undefined method each' for nil:NilClass error. 我在这里做错了什么?

class TidbitsController < ApplicationController
     before_filter :is_admin?
     layout "tidbits"
      # GET /tidbits
      # GET /tidbits.json
      protected    
      def is_admin?
        unless current_user.admin?
         flash[:error] = "You are not authorized!"
         redirect_to "/" and return
        end
      end

      def index
        @tidbits = Tidbit.all

        respond_to do |format|
          format.html # index.html.erb
          format.json { render json: @tidbits }
        end
      end

      # GET /tidbits/1
      # GET /tidbits/1.json
      def show
        @tidbit = Tidbit.find(params[:id])

        respond_to do |format|
          format.html # show.html.erb
          format.json { render json: @tidbit }
        end
      end

      # GET /tidbits/new
      # GET /tidbits/new.json
      def new
        @tidbit = Tidbit.new

        respond_to do |format|
          format.html # new.html.erb
          format.json { render json: @tidbit }
        end
      end

      # GET /tidbits/1/edit
      def edit
        @tidbit = Tidbit.find(params[:id])
      end

      # POST /tidbits
      # POST /tidbits.json
      def create
        @tidbit = Tidbit.new(params[:tidbit])

        respond_to do |format|
          if @tidbit.save
            format.html { redirect_to @tidbit, notice: 'Tidbit was successfully created.' }
            format.json { render json: @tidbit, status: :created, location: @tidbit }
          else
            format.html { render action: "new" }
            format.json { render json: @tidbit.errors, status: :unprocessable_entity }
          end
        end
      end

      # PUT /tidbits/1
      # PUT /tidbits/1.json
      def update
        @tidbit = Tidbit.find(params[:id])

        respond_to do |format|
          if @tidbit.update_attributes(params[:tidbit])
            format.html { redirect_to @tidbit, notice: 'Tidbit was successfully updated.' }
            format.json { head :no_content }
          else
            format.html { render action: "edit" }
            format.json { render json: @tidbit.errors, status: :unprocessable_entity }
          end
        end
      end

      # DELETE /tidbits/1
      # DELETE /tidbits/1.json
      def destroy
        @tidbit = Tidbit.find(params[:id])
        @tidbit.destroy

        respond_to do |format|
          format.html { redirect_to tidbits_url }
          format.json { head :no_content }
        end
      end

    end
4

2 回答 2

2

在您的示例中,您所有的操作方法都是protected如此,也许这就是问题所在?

于 2012-09-10T22:58:10.500 回答
0

我认为您忘记添加设计所需的回调过滤器

before_filter :authenticate_user!
before_filter :is_admin?
于 2012-09-10T23:08:28.080 回答