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

时间:2013-02-19 02:15:21

标签: ruby-on-rails ruby cancan

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

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

# 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

1 个答案:

答案 0 :(得分:2)

而不是can? :manage, Course,您可以使用can? :manage, Course.new并确保新课程对象无法通过您在ability.rb中传递的块