So I got CanCan and Devise working well. I have two types of users:
Admins and Nonadmins. Admins can edit all of Nonadmins profiles.
The problem is, every user (either Admin or Nonadmin) belongs to an
Account or Organization. Admins should only be able to edit users from
their own Account or Organization. I was able to do that too.
The problem is, I can’t display the Create New User link. It seems
everything is correct but I must be doing something wrong.
HERE IS ABILITY.RB
if user.role == "admin"
can :read, User do |u|
u.try(:account_id) == user.account_id
end
can :update, User do |u|
u.try(:account_id) == user.account_id
end
can :destroy, User do |u|
u.try(:account_id) == user.account_id
end
can :create, User
In your code:
<% if can? :create, @user %>
I believe that @user is nil, so when your Ability.rb try’s to
read :account_id, it returns nil, and it is never == user.account_id,
thus your link is not displayed.
I don’t know if it’s the correcto solution, but I’m adding new
abilities.
In your case, you could use a create_user ability, and check it
against the Account in question.
So in Ability.rb:
if user.role == “admin”
can :create_user, Account do |acc|
acc.id == user.account_id
end
And in your view:
link_to “New user”, … if can? :create_user, account # you have to
set the account variable somewhere.
Note that you don’t have to “create” the :create_user ability. You can
just use it.
FWIW, these are the only actions included by default in CanCan
(no :write!)
I think you may need to change the object that can? is evaluating from the @user variable to the class User like so:
<% if can? :create, User %>
This would allow an admin to create any use regardless of the account
it
belongs to and that is not what , he wants.
What i have notice is that cancan is very picky when you specify an
action
so try using others that have the same effect like write.
<% if can? :write, @user %>
What do you mean? What does write do? I have been searching for a list
of abilites but haven’t found one. All I see is that they use the 7
RESTful resources. Can you point me to a list of abilities that work
with CanCan?
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.