Ruby on rails 使用CanCan基于多对多关联授权资源
我有两个模型,事件和用户共享多对多关联。用户可以是管理员、经理或制作人。 只有属于某个事件的生产者才能读取该事件。我试图在能力模型上应用该限制,但失败了,每个制作人都可以读取所有事件。我做错了什么Ruby on rails 使用CanCan基于多对多关联授权资源,ruby-on-rails,many-to-many,authorization,cancan,Ruby On Rails,Many To Many,Authorization,Cancan,我有两个模型,事件和用户共享多对多关联。用户可以是管理员、经理或制作人。 只有属于某个事件的生产者才能读取该事件。我试图在能力模型上应用该限制,但失败了,每个制作人都可以读取所有事件。我做错了什么 class Event < ActiveRecord::Base has_and_belongs_to_many :producers, :class_name => "User", :join_table => "events_producers" end class Cre
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
class事件“User”,:join_table=>“events_producer”
结束
类CreateEventUserJoinTablefalse do | t|
t、 整数:事件\u id
t、 整数:用户id
结束
结束
def自动关闭
drop_表:事件\u生产者
结束
结束
班级能力
包括CanCan::能力
def初始化(用户)
user | |=user.new()#来宾用户
如果user.role?:经理
can:manage,:all
elsif user.role?:管理
can:读取,事件
can:更新,事件
can:创建,事件
elsif user.role?:制作人
can:读取,事件执行|事件|
事件。尝试(:生产者)。包括?(用户)
结束
结束
结束
结束
问题在于,当基于类的调用时,能力块中的条件没有被使用,例如索引操作。有关澄清,请参阅
对于索引操作,必须在块外定义限制 您的问题有点老,但如果不使用块,您可以这样定义上述条件:
can :read, Event, :producers => {:user_id => user.id}
除此之外,不需要询问用户是否具有生产者角色