I am using cancan with one role per user. The roles are integers instead of strings. My ability.rb is organized like this:
def initialize(user, session)
if user.role.to_i == 9
can :create, [Resource1, Resource2, Resource3]
can :update, [Resource1, Resource2, Resource3]
elsif user.role.to_i == 8
can :create, [Resource1, Resource2]
can :update, [Resource1, Resource2]
else
can :create, Resource1
can :update, Resource1
end
end
In reality there are 7 roles instead of 3 and the file is much more complex. Could the file be rewritten like this instead so a role can be defined cumulatively through the conditional statements?
def initialize(user, session)
if user.role.to_i >= 9
can :create, Resource3
can :update, Resource3
end
if user.role.to_i >= 8
can :create, Resource2
can :update, Resource2
end
can :create, Resource1
can :update, Resource1
end
I’d like to know if this EXACT structure with the conditional statements would work before i rewrite the entire file. Thanks.
Yes (except for the comparison). Look here, it adds the rule.
Edit: In case it may be useful.
Edit 2:
What does the first part mean?
In first place, sorry for pasting the wrong chunk of code. Then, you can see you are adding a new rule whose subject is the one you passed to
can. InRuleinitializer, you can see the line:that means that if you had an array you still have that array (that’s what
flattenis for), but if you had only one resource you get a one-item array. You can dig more in the code and you will notice than a rule with one resource behaves as a rule with only one.Then this rule is added to
ruleswithout replacing any other.Hope is clear now.