【问题标题】:Cancan rolify : Defining ability to update resource attribute with blockCancan rolify : 定义用块更新资源属性的能力
【发布时间】:2014-08-21 10:47:26
【问题描述】:

我一直坚持这一点,但我没有得到可以使它工作的语法。 我想授权用户根据他在关联中的角色更新实例的属性。

我尝试过类似的方法,但在尝试更新其他属性时不会引发错误

用户模型

class User < ActiveRecord::Base
  rolify
 ...
end

项目模型

class Project < ActiveRecord::Base
  resourcify
  has_many :stories, dependent: :destroy
 ...
end

故事模型

class Story < ActiveRecord::Base
  belongs_to :project
  ...
end

故事控制器

class StoriesController < ApplicationController
  ...
  def update
    story = Project.find(params[:project_id]).stories.find(params[:id])
    authorize! :update, story

    if story.update_attributes(story_params)
      render json: story
    else
      render status: :unprocessable_entity, json: {errors: story.errors}
    end
  end
 ...
end

能力.rb

def initialize(user)

    @user = user || User.new
    can :update, Story, :points do |s|
       @user.has_role?(:team_member, s.project)
     end

end

【问题讨论】:

  • 请用文字告诉你想要用这个 |s| 达到什么目的@user.has_role?(:team_member, s.project)
  • |s| @user.has_role?(:team_member, s.project) 是检查用户是否在获得此故事的项目中具有 team_member 角色...等等,我将使用更多模型和控制器代码更新问题
  • 您使用的是哪个版本的 CanCan?未发布的 2.x 分支?
  • 最新的 Gemfile.lock 说 cancancan (1.9.1)

标签: ruby-on-rails cancan rolify


【解决方案1】:

现在,您的能力与能力.rb 文件紧密耦合。每次您需要添加或更改角色(或能力)时,您都必须更改代码。

您可以为您的角色添加权限(作为新的另一个模型或只是一个 json 字段)并在能力的初始化程序中对其进行迭代。

  user.roles.each do |role|
    role.permissions.each do |rights, value|
      value.each do |action, subject|
        case rights
        when "can"
          subject == 'all' ? (can action.to_sym, :all) : (can action.to_sym, subject.classify.constantize)
        when "cannot"
          subject == 'all' ? (cannot action.to_sym, :all) : (cannot action.to_sym, subject.classify.constantize)
        end
      end
    end
  end

因此,您将能够在数据库中存储权限,使用一些管理面板等进行编辑。在您的情况下,它可能看起来像:

 # @user.roles.find_by_name('team_member').permissions
 'can' => { 'update' => 'story' }      

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    相关资源
    最近更新 更多