Search code examples
ruby-on-railscancan

Ruby CanCan ability with multiple subjects (classes)?


How to have multiple subjects to Cancan ability ?

I'd like to define ability as:

can :change_role, Project, Document  do |prj, doc|
   # my logic here
   ..
end

So i check it like this:

prj1 = Project.find(10)
doc1 = Document.find(...)

user.can? :change_role, prj1,  doc1 

And it doesn't work.

But Cancan allows only this:

can :read, Project do |prj|
  ..
end

user.can? :read, prj1

Should I create my proxy class to store two subjects and pass it to ability ?

How to add abilities with multiple classes/subjects ?


Solution

  • do this:

    user.can? :change_role, [prj1, doc1]
    

    define Ability:

    can :change_role, Array do |p|
      prj = p[0]
      doc = p[1]
      ...
    end