classUser<ActiveRecord::Baserolify# Include default devise modules. Others available are:# :confirmable, :lockable, :timeoutable and :omniauthabledevise:database_authenticatable,:registerable,:recoverable,:rememberable,:trackable,:validatableend
裡面有些是預設沒打開的,像是寄認證信之類的,需要再打開設定就可以了,migration 也是。
也可以自行在 model 增加欄位,因為預設的可能是比較基本的。
User.with_role(:admin)#找單一權限User.with_any_role(:user,:admin)#找 a or b 權限User.with_all_roles(:user,:admin)#找 a + b 權限
對 resource 設定角色權限
可以直接指定這個權限可以進入哪些 resource
先在要設定的 model 裡
In the resource models you want to apply roles on, just add resourcify method. For example, on this ActiveRecord class:
123
classForum<ActiveRecord::Baseresourcifyend
這樣就可以設定自己才可以看到自己的資料
1234567891011
user.add_role:moderator,Forum.first#設定為第一個 Forum 的 resourceuser.has_role?:moderator,Forum.first#=> trueuser.has_role?:moderator,Forum.last#=> falseuser.add_role:moderator,Forum#設定為所有的 Forum 的 resource
resource 角色權限查詢
Instance level
12345
forum=Forum.firstforum.roles# => [ list of roles that are only binded to forum instance ]forum.applied_roles# => [ list of roles binded to forum instance and to the Forum class ]
Class level
12345678910111213141516171819202122
Forum.with_role(:admin)# => [ list of Forum instances that has role "admin" binded to it ]Forum.with_role(:admin,current_user)# => [ list of Forum instances that has role "admin" binded to it and belongs to current_user roles ]Forum.with_roles([:admin,:user],current_user)# => [ list of Forum instances that has role "admin" or "user" binded to it and belongs to current_user roles ]User.with_any_role(:user,:admin)# => [ list of User instances that has role "admin" or "user" binded to it ]User.with_role(:site_admin,current_site)# => [ list of User instances that have a scoped role of "site_admin" to a site instance ]User.with_role(:site_admin,:any)# => [ list of User instances that have a scoped role of "site_admin" for any site instances ]User.with_all_roles(:site_admin,:admin)# => [ list of User instances that have a role of "site_admin" and a role of "admin" binded to it ]Forum.find_roles# => [ list of roles that binded to any Forum instance or to the Forum class ]Forum.find_roles(:admin)# => [ list of roles that binded to any Forum instance or to the Forum class with "admin" as a role name ]Forum.find_roles(:admin,current_user)# => [ list of roles that binded to any Forum instance or to the Forum class with "admin" as a role name and belongs to current_user roles ]
Callbacks
12345678910111213
classUser<ActiveRecord::Baserolify:before_add=>:before_add_methoddefbefore_add_method(role)# do something before it gets addedendend#四種 callbacks#before_add#after_add#before_remove#after_remove