如何在不定义类能力的情况下在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
答案 0 :(得分:2)
而不是can? :manage, Course
,您可以使用can? :manage, Course.new
并确保新课程对象无法通过您在ability.rb中传递的块