$ rails g cancan:ability
create app/models/ability.rb
#app/models/ability.rbclass Ability
include CanCan::Ability
def initialize(user)# Define abilities for the passed in user here. For example:
#
# user ||= User.new # guest user (not logged in)
# if user.admin?
# can :manage, :all
# else
# can :read, :all
# end
#
# The first argument to `can` is the action you are giving the user permission to do.
# If you pass :manage it will apply to every action. Other common actions here are
# :read, :create, :update and :destroy.
#
# The second argument is the resource the user can perform the action on. If you pass
# :all it will apply to every resource. Otherwise pass a Ruby class of the resource.
#
# The third argument is an optional hash of conditions to further filter the objects.
# For example, here the user can only update published articles.
#
# can :update, Article, :published => true
#
# See the wiki for details: https://github.com/ryanb/cancan/wiki/Defining-Abilitiesend
end
3.创建Role model
$ rails g model role
4.User和Role之间添加关联
class User
include Mongoid::Document
...
embeds_many:roles
...
end
class Role
include Mongoid::Document
field :name
embedded_in :user
end
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.newif user.role? :admin
can :manage, :all
elsif user.role? :user
can :read, Forum
end
end
end
7.编辑需要添加权限的controller
class ForumsController < ApplicationController
before_filter :authenticate_user!
#load_and_authorize_resource 和 authorize_resource 两个方法都可以,不同的是load_and_authorize_resource会先加载本类model的值
authorize_resource
def index
@forums = Forum.all()#authorize! :read, @forums 对单个action进行权限判断end
def new
@forum = Forum.newend
end
也可以在view中进行权限判断,方法是can? 和 cannot?
# app/views/forums/index.html.haml- if can? :create, @forums
= link_to "创建", new_forum_path
class ApplicationController < ActionController::Base
...
rescue_fromCanCan::AccessDenied do |exception|
redirect_to root_url, :alert => exception.messageend
...
end