【问题标题】:Using CanCan to authorize a resource based on a many to many association使用 CanCan 授权基于多对多关联的资源
【发布时间】:2012-11-16 21:20:20
【问题描述】:

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

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

【问题讨论】:

    标签: ruby-on-rails many-to-many authorization cancan


    【解决方案1】:

    你的问题有点老了,但没有块使用,你可以像这样定义上述条件:

    can :read, Event, :producers => {:user_id => user.id}
    

    除了该行之外,不需要询问用户是否具有生产者角色。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 2021-09-29
        • 2013-09-22
        • 2021-08-31
        • 1970-01-01
        相关资源
        最近更新 更多