Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define instance abilities in cancan without defining class abilities?

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
like image 568
peter Avatar asked Mar 22 '26 17:03

peter


1 Answers

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

like image 176
jvnill Avatar answered Mar 25 '26 09:03

jvnill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!