在我的应用程序中,我想只允许具有管理员权限的用户访问此模型。所以我设置了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
答案 0 :(得分:2)
在您的示例中,您的所有操作方法都是protected
所以也许这就是问题?
答案 1 :(得分:0)
我认为您忘记添加设计所需的回调过滤器
before_filter :authenticate_user!
before_filter :is_admin?