How do I define instance abilities in cancan without defining class abilities?
如何定义cancan中的实例能力而不定义类能力?
I want to allow the :manage
action for particular Course
instances, not the Course
class.
我想允许:针对特定的课程实例管理操作,而不是课程类。
# ability.rb
can :manage, Course do |course|
# Check if the user is a helper for this course
CourseRole.get_role(user, course) == "helper"
end
This works fine for instance variables:
这适用于实例变量:
# some_view.rb
can? :manage, @course # checks the instance to see if :manage is allowed
But if I do this:
但如果我这样做:
# some_view.rb
can? :manage, Course
it always returns true, which is bad.
它总是返回true,这很糟糕。
Some context:
一些背景:
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 个解决方案
#1
2
instead of can? :manage, Course
, you can use can? :manage, Course.new
and be sure that new course objects fail the block you passed in ability.rb
代替可以吗?:管理,当然,你可以用can吗?:管理课程。新并确保新课程对象失败了您在ability.rb中传递的块
#1
2
instead of can? :manage, Course
, you can use can? :manage, Course.new
and be sure that new course objects fail the block you passed in ability.rb
代替可以吗?:管理,当然,你可以用can吗?:管理课程。新并确保新课程对象失败了您在ability.rb中传递的块