zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    OC与JS交互之WKWebView
    iOS下JS与OC互相调用(三)--MessageHandler
    html base64 img 图片显示
    Vue中img的src属性绑定与static文件夹
    XML 树结构
    XML 用途
    XML 简介
    JS Window对象
    JS Math对象
    JS 字符串操作
  • 原文地址:https://www.cnblogs.com/wangyuyu/p/3412220.html
Copyright © 2011-2022 走看看