cancan是一款rails的权限认证gem,非常的强大和灵活。权限可以定义在代码中,也可以定义到数据库中。 与分级插件awesome_nested_set配合能完成非常复杂的用户权限控制。
config.gem "cancan"
gem 'cancan'
class Ability include CanCan::Ability def initialize(user) end end
rails g cancan:ability
can :read, Project, :active => true, :user_id => user.id定义nested嵌套属性
can :read, Project, :category => { :visible => true }block定义属性
can :update, Project do |project| project.priority < 3 end重写can 方法?!
can do |action, subject_class, subject| # ... end
load_and_authorize_resource :users, :photo user = User.accessible_by(current_ability).find(:first, :conditions => ["username = ?", @username])
def show @article = Article.find(params[:id]) authorize! :read, @article end
class ApplicationController < ActionController::Base check_authorization end
<% if can? :update, @article %> <%= link_to "Edit", edit_article_path(@article) %> <% end %>
class ApplicationController < ActionController::Base rescue_from CanCan::AccessDenied do |exception| redirect_to root_url, :alert => exception.message end end
资料:
cancan homepage: https://github.com/ryanb/cancan
awesome_nested_set home page: https://github.com/collectiveidea/awesome_nested_set
devise, cancan , bootstrap rails3.2 整合: https://github.com/RailsApps/rails3-bootstrap-devise-cancan