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