首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用CanCan根据多对多关联对资源进行授权

使用CanCan根据多对多关联对资源进行授权
EN

Stack Overflow用户
提问于 2011-05-06 06:53:41
回答 2查看 4.4K关注 0票数 3

我有两个共享多对多关联的模型、事件和用户。用户可以是管理员、经理或制作人。只有属于某个事件的生产者才能读取该事件。我试图将该限制应用于能力模型,但它失败了,每个生产者都可以读取所有事件。我做错了什么?

代码语言:javascript
复制
class Event < ActiveRecord::Base
 has_and_belongs_to_many :producers, :class_name => "User", :join_table => "events_producers"
end


class CreateEventUserJoinTable < ActiveRecord::Migration
  def self.up
    create_table :events_producers, :id => false do |t|
      t.integer :event_id
      t.integer :user_id
    end
  end

  def self.down
    drop_table :events_producers
  end
end

class Ability
  include CanCan::Ability
  def initialize(user)
    user ||= User.new() # Guest user
    if user.role? :manager
      can :manage, :all
    elsif user.role? :admin
      can :read, Event
      can :update, Event
      can :create, Event
    elsif user.role? :producer
      can :read, Event do |event|
          event.try(:producers).include?(user)
        end
    end
  end
end
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-09-01 00:42:47

问题是,当基于类的调用时,能力块中的条件不会被使用,例如索引操作。有关说明,请参阅https://github.com/ryanb/cancan/wiki/Defining-Abilities-with-Blocks

对于索引操作,必须在块之外定义限制。

票数 0
EN

Stack Overflow用户

发布于 2012-11-16 21:20:21

你的问题有点陈旧,但没有块使用,你可以像这样定义上面的条件:

代码语言:javascript
复制
can :read, Event, :producers => {:user_id => user.id}

此外,应该不需要询问用户是否具有生产者角色。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5904996

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档