ruby on rails 权限管理gem cancan

系统的model关系如下:

用户类

class AdminUser

  embeds_many :permissions
  accepts_nested_attributes_for :permissions, :allow_destroy => true

end

 

用户能力类

class Ability
  include CanCan::Ability

  def initialize(user)

  can do |action, subject_class, subject|
  end

 

权限类

class Permission
  include Mongoid::Document
  embedded_in :admin_user

end

首先添加gem: gem "cancan"

admin_user/new.html.erb 新建如下

在新建用户的同时,新建用户对应的权限(复选框为选择权限)

mongoid的 accepts_nested_attributes_for 可以省去很多事。

在mall/index.html.erb 加判断

<% if can? :create, Mall %>
    <%= link_to '新建', new_admin_mall_path(), :class => 'btn btn-primary' %>
<% end %>

如果用户有权限新建,新建按钮会显示出来,否则按钮不会出现。

这样的话还有一个问题,能不能在地址栏直接输入http://localhost:3000/admin/malls/new,执行一个新建操作?

为了防止这种情况,我们必须 Protecting malls_Controller.rb

在new方法加入 authorize! if cannot? :new, Mall,防止地址栏执行action.

def new
    @mall = Mall.new
    authorize! if cannot? :new, Mall

end

 

这样一个简易的用户权限管理功能就做好了。

JUST DO IT

posted @ 2013-11-07 12:13  wangyuyu  阅读(2445)  评论(0编辑  收藏  举报