当前位置 : 主页 > 编程语言 > ruby >

ruby-on-rails – 使用CanCan基于多对多关联来授权资源

来源:互联网 收集:自由互联 发布时间:2021-06-23
我有两个模型,事件和用户共享多对多关联.用户可以是管理员,经理或制作人. 只有属于某个事件的生产者才能读取该事件.我试图在能力模型上应用这种限制,但它失败了,每个制作人都可
我有两个模型,事件和用户共享多对多关联.用户可以是管理员,经理或制作人.
只有属于某个事件的生产者才能读取该事件.我试图在能力模型上应用这种限制,但它失败了,每个制作人都可以阅读所有事件.我究竟做错了什么?

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
问题在于,当基于类的呼叫(例如,基于类的呼叫)时,不使用能力块中的条件.索引动作.有关说明,请参见 https://github.com/ryanb/cancan/wiki/Defining-Abilities-with-Blocks.

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

网友评论