在我的應用程序中,我只想讓具有管理員權限的用戶訪問此模型。所以我設置了before_filter來檢查用戶是否是Admin。這種方法的問題在於,在admin用戶通過過濾器之後,他/她將無法重定向到該操作。相反,只有視圖被渲染,這導致了undefined method each' for nil:NilClass error
。我在這裏做錯了什麼?Rails before_filter未命中數據庫
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
我不知道怎麼感謝你了。但我記得把is_admin?方法直到底部,它也無法工作。儘管如此,當我把它搬下來的時候,它就起作用了! – zsljulius