3

如何在不定义类能力的情况下在 cancan 中定义实例能力?

我想允许:manage特定Course实例的操作,而不是Courseclass

# ability.rb
can :manage, Course do |course|
  # Check if the user is a helper for this course
  CourseRole.get_role(user, course) == "helper"
end

这适用于实例变量:

# some_view.rb
can? :manage, @course # checks the instance to see if :manage is allowed

但如果我这样做:

# some_view.rb
can? :manage, Course 

它总是返回 true,这很糟糕。

一些上下文:

class User < ActiveRecord::Base
  has_many :course_roles
  has_many :courses, :through => :course_roles
  ...
class CourseRoles < ActiveRecord::Base
  belongs_to :user
  belongs_to :course
  ...
class Courses < ActiveRecord::Base
  has_many :course_roles
  has_many :users, :through => :course_roles
4

1 回答 1

2

而不是can? :manage, Course,您可以使用can? :manage, Course.new并确保新课程对象无法通过您传入的 block 能力.rb

于 2013-02-19T02:44:08.850 回答