Reputation: 6137
How do I define instance abilities in cancan without defining class abilities?
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.
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
Upvotes: 3
Views: 323
Reputation: 29599
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
Upvotes: 2