从 CanCan 等访问 Devise 辅助方法
这似乎是一个简单的问题,我就是无法理解。
在新的 Rails 3 应用程序上使用 Devise 进行身份验证,使用 CanCan 进行授权。
如何访问 CanCan 提供的 Ability
类中的 ApplicationController
中定义的方法?
又名,类似这样的:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # Guest user.
can :create, Post if user_signed_in?
end
end
其中 user_signed_in?
是在 ApplicationController
中定义的。
This seems like an easy question that I just can't wrap my head around.
Using Devise for authentication and CanCan for authorization on a new Rails 3 app.
How can I access methods defined in ApplicationController
within the Ability
class that CanCan provides?
a.k.a., something like this:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # Guest user.
can :create, Post if user_signed_in?
end
end
where user_signed_in?
is defined in ApplicationController
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能不是您想要的答案,但您似乎想要混合不应该混合的代码问题。
在授权规则中访问
user_signed_in?
是个好主意吗? ...因为授权只关心某人可以做什么,而不应该关心某人是否经过身份验证(或未经过身份验证)。您的帖子控制器上的 before 过滤器 (
before_filter :authenticate_user!
) 用于检查您的用户是否已通过身份验证,这应该足以实现您的目标;您的授权规则可以与身份验证检查一起运行,而不是与其代码混合在一起。这是一种分层方法:-)
This might not be the answer you wanted, but it seems like you are wanting to mix code concerns that shouldn't be mixed.
Is it a good idea to access
user_signed_in?
inside your authorisation rules? ... Since authorisation is only concerned with what someone can do, and should not be concerned with if that someone is authenticated (or not).A before filter (
before_filter :authenticate_user!
) on your Posts controller to check that your user is authenticated should be enough to do achieve your objective; Your authorisation rules can be run alongside the authentication check, rather than mixed up with it's code.It's a layered approach :-)