Get a string that represents a user's CanCan abilities

前端 未结 2 1707
名媛妹妹
名媛妹妹 2021-02-01 10:07

I want to cache a Post view, but the view depends on the permissions of the current user (e.g., I only show the \"edit\" link if current_user.can?(:edit, @pos

2条回答
  •  遥遥无期
    2021-02-01 10:26

    I wanted to send my abilities to JS, and to follow up on this post, here's my helper method that you can use to convert your user abilities to an array in your controller. I then call .to_json on the array an pass it to javascript.

    def ability_to_array(a)
      a.instance_variable_get("@rules").collect{ |rule| 
      { 
        :subject => rule.instance_variable_get("@subjects").map { |s| s.name }, 
        :actions => rule.instance_variable_get("@actions").map { |a| a.to_s }
      }
    }
    end
    

    And here's my Backbone.js model that implements the can() method:

    var Abilities = Backbone.Model.extend({
      can : function(action, subject)
      {
        return _.some(this.get("abilities"), function(a) {
          if(_.contains(a["actions"], "manage") && _.contains(a["subject"], "all")) return true;
          return _.contains(a["actions"], action) && _.contains(a["subject"], subject);
        });
       }
    });
    

提交回复
热议问题