[英]CanCan + Devise for the devise user model
Using devise , I have a User model. 使用devise ,我有一个用户模型。 I do not have a user controller. 我没有用户控制器。
To use CanCan I need to do (below) at the top of my controllers 要使用CanCan,我需要在控制器顶部执行以下操作
# Authorization w Devise & CanCan
before_filter :authenticate_user! # Devise, signed in users only
load_and_authorize_resource # CanCan
Where do I add this so I can have permissions for the User model given I have no user controller? 我在哪里添加它,以便在没有用户控制器的情况下可以拥有User模型的权限?
Thanks 谢谢
You can add that code to any controller for which you need authentication, you don't need an UsersController
您可以将该代码添加到需要身份验证的任何控制器中,不需要UsersController
before_filter :authenticate_user!
this line require a valid user signed in with devise, so if you try to access a controller with this before_filter without being logged you'll be redirected by devise to the sign_in_path
该行要求使用sign_in_path
登录的有效用户,因此,如果您尝试使用before_filter来访问控制器而未登录,则将被sign_in_path
重定向到sign_in_path
load_and_authorize_resource # CanCan
this other line will fill an instance variable to a default value (if not already set) and then check your privileges using the Ability
class, so assuming you have an ArticleController
it will do the following behind the scenes (actual code is based on the current action) 另一行将实例变量填充为默认值(如果尚未设置),然后使用Ability
类检查特权,因此,假设您有ArticleController
,它将在后台执行以下操作(实际代码基于当前行动)
# for the show action
@article = Article.find(params[:id])
raise CanCan::AccessDenied unless can(:read, @article)
The can(:read, @article)
statement is the hearth of CanCan library, it will return a boolean value based on your ability class. can(:read, @article)
语句是CanCan库的壁炉,它将根据您的能力等级返回布尔值。 Can read more on it here 可以在这里阅读更多内容
If your whole application requires authentication you can simply add the before_filter :authenticate_user!
如果整个应用程序都需要身份验证,则只需添加before_filter :authenticate_user!
line to the ApplicationController
行到ApplicationController
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.