Cir*_*des 3 authorization many-to-many ruby-on-rails cancan
我有两个模型,事件和用户共享多对多关联.用户可以是管理员,经理或制作人.只有属于某个事件的生产者才能读取该事件.我试图在能力模型上应用这种限制,但它失败了,每个制作人都可以阅读所有事件.我究竟做错了什么?
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
Run Code Online (Sandbox Code Playgroud)
你的问题有点旧,但没有块使用,你可以定义上述条件:
can :read, Event, :producers => {:user_id => user.id}
Run Code Online (Sandbox Code Playgroud)
除此之外,不应该询问用户是否具有生产者角色.