Ruby on rails Rails-使页面仅可供管理员查看
我有一个非常简单的问题。我有一个页面列出了我应用程序中的所有产品。我只想让管理员只能查看页面。但我希望每个人都能清楚地看到产品/新产品 schema.rbRuby on rails Rails-使页面仅可供管理员查看,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,我有一个非常简单的问题。我有一个页面列出了我应用程序中的所有产品。我只想让管理员只能查看页面。但我希望每个人都能清楚地看到产品/新产品 schema.rb create_table "users", :force => true do |t| t.string "email" t.string "password_hash" t.string "password_salt" t.datetime "created_at", :nul
create_table "users", :force => true do |t|
t.string "email"
t.string "password_hash"
t.string "password_salt"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "name"
t.boolean "admin", :default => false
end
产品控制器
class ProductsController < ApplicationController
before_filter :require_login
before_filter :current_user, only: [:create, :destory]
before_filter :correct_user, only: :destory
def index
@products = Product.all
end
def new
@product = Product.new
end
def create
@product = current_user.products.new(params[:product])
if @product.valid?
@product.save
render "show", :notice => "Sale created!"
else
render "new", :notice => "Somehting went wrong!"
end
end
class ProductsController“Sale created!”
其他的
呈现“新建”:注意=>“出现了一些错误!”
结束
结束
放入控制器
before_filter :authorize_admin, only: :index
和应用程序中的_controller.rb
def authorize_admin
redirect_to :back, status: 401 unless current_user.admin
#redirects to previous page
end
查看Railscasts的插曲
事实上,Ryan Bates是从头开始进行身份验证的忠实粉丝,他就这个话题发表了自己的看法。看看它们,你肯定会有一些好主意。你试过什么?这并不是一个发人深省的问题,您有一个用于admin的布尔值,并且您只想将操作限制为admin,所以只需选中
current\u user.admin
before_filter :require_admin, only: :index
private
def require_admin
if !current_user.admin
if request.xhr?
head :unauthorized # for asynchronous/api requests, if you want.
else
render 'access/no_access' and return # or whatever.
end
end
end
在ProductsController中,您可以添加一个函数来验证用户是否为管理员,并对要保护的视图使用筛选器,如下所示:
class ProductsController < ApplicationController
before_filter :admin_user, only: :index # here you specify the action (for views) to protect
.
.
.
private
.
.
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
class ProductsController
我希望能帮助你在你的控制器上写 前过滤器:管理员用户 创建一个像这样的def
private
def admin_user
redirect_to(root_path) unless current_user && current_user.admin?
end
在控制器上的private下添加
correct_user
方法和admin_user
方法,或创建另一个具有以下定义的方法,并添加:only=>:index
onon\u filter
for admin
before_filter :require_login
before_filter :correct_user
before_filter :admin_user, :only => :index
private
def correct_user
redirect_to(root_path) if current_user.nil? && !current_user.admin?
end
def admin_user
redirect_to(root_path) unless current_user.admin?
end
如果你使用Desive来进行身份验证,那么你可以使用内置的帮助程序:authenticate\u user,关于管理,请看这个,我不使用Desive,因为它说只有有经验的rails开发人员才应该使用它,这是我的第一个非教程应用程序。不要听这个,我想Deave的文档会解释所有级别的所有内容,跳进去,最坏的情况是什么?@Richlewis,最坏的情况是他学习了Sweet FA。或者他可能真的学到了一些新东西……哇,别太疯狂了:)从他的模式来看,他已经有了一些认证。@MikeCampbell我不这么认为。如果你不想看整个视频。改为阅读AsciCast,没有显示注释。我是说OP。再次阅读他的问题。他的用户表已经有admin属性。仔细查看模式