kibaekr
kibaekr

Reputation: 1349

Rails: How to check if certain user has Ability using CanCan

I know when you want to check the ability, you do

can :read, Project, id:3

However, what if I wanted to create a page that showed all the users that could read Project #3?

In that page, how would I show all the users that had :read access to the specific project?

Something like

 <% User.all.each do |u| %>
   <% if u can :read, Project, id:3 %>
     <%= u.name %>
   <% end %>
 <% end %>

Upvotes: 1

Views: 2929

Answers (3)

TlmaK0
TlmaK0

Reputation: 3886

you can check with this:

Ability.new(u).can? :read, project

Upvotes: 3

Ecnalyr
Ecnalyr

Reputation: 5802

Cancan has documentation for this: https://github.com/ryanb/cancan/wiki/Checking-Abilities

Based on your example:

include CanCan::Ability
project = Project.find(3)
User.all.each do |u|
    if u.can? :read, project
      #print the user or something
    end
end

Upvotes: 0

kibaekr
kibaekr

Reputation: 1349

Looks like there was a wiki on this issue:

https://github.com/ryanb/cancan/wiki/ability-for-other-users

Upvotes: 0

Related Questions