我有两个共享多对多关联的模型、事件和用户。用户可以是管理员、经理或制作人。只有属于某个事件的生产者才能读取该事件。我试图将该限制应用于能力模型,但它失败了,每个生产者都可以读取所有事件。我做错了什么?
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发布于 2011-09-01 00:42:47
问题是,当基于类的调用时,能力块中的条件不会被使用,例如索引操作。有关说明,请参阅https://github.com/ryanb/cancan/wiki/Defining-Abilities-with-Blocks。
对于索引操作,必须在块之外定义限制。
发布于 2012-11-16 21:20:21
你的问题有点陈旧,但没有块使用,你可以像这样定义上面的条件:
can :read, Event, :producers => {:user_id => user.id}此外,应该不需要询问用户是否具有生产者角色。
https://stackoverflow.com/questions/5904996
复制相似问题