系統的model關係以下:html
用戶類htm
class AdminUserblog
embeds_many :permissions
accepts_nested_attributes_for :permissions, :allow_destroy => trueget
endit
用戶能力類io
class Ability
include CanCan::Ability
def initialize(user)class
can do |action, subject_class, subject|
endmodel
權限類權限
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