2011-05-05 120 views
2

我有两个共享多对多关联的模型,事件和用户。用户可以是管理员,经理或制片人。 只有属于某个事件的生产者才能够读取该事件。我试图在能力模型上应用这个限制,但它失败了,每个生产者都可以阅读所有事件。我究竟做错了什么?使用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 

回答

6

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

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

除了与该行,它应该没有必要问,如果用户有一个生产者的角色。