作者giive (lala)
看板Ruby
标题[RoR ] RoR Access Control : before_filter
时间Wed Sep 13 13:03:24 2006
http://lightyror.blogspot.com/2006/09/ror-access-control-beforefilter.html
基本上,RoR要做到 Access Control 的部份
使用 before_filter 是最简单的方式
before_filter 就是当你进入这个 controller
他会先经过这个 filter
然後才会执行相关的 action
所以我们可以在 before_filter 里面
加入 session 里面是不是有 user 资料
如果没有,导入到 login 页面
如果有,就直接自动执行
范例,一个 Controller 名字叫做 Apple ,他里面要做 access control
class AppleController < ActionController::Base
before_filter :authorize
def authorize
redirect_to :controller => 'login' , :action => 'index' unless session[:user]
end
end
但是问题来了
今天一堆 controller
如果每个都得加上 before_filter
那不是加到累死了
而且严重违反 DRY 准则
所以我们想到了
所有controller 都继承 ApplicationController
那我们加到 ApplicationController 里面就好了
class ApplicationController < ActionController::Base
before_filter :authorize
def authorize
redirect_to :controller => 'login' , :action => 'index' unless session[:user]
end
end
呵呵,这样就万事大成了吗?
怎麽浏览器不动了?
看看 log ,发现到 before_filter 的确 work
但是就连我们的登入页面 LoginController 里面的 index action 进入 before filter
所以呈现一个无穷回圈
要怎麽做呢?
其实我们只要每个 controller 都有 before filter
但是 login controller 不需要 before filter 即可
class LoginController < ActionController::Base
skip_before_filter :authorize
.....
.....
.....
end
我们在 LoginController 里面使用 skil_before_filter 将 before_filter skip 掉
大功告成!!!
--
lighty RoR 是一个介绍 lighttpd , SQLite , Ruby and Rails 的 Blog
http://lightyror.blogspot.com/
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 61.218.90.242