Aayush
Aayush

Reputation: 1254

Rails : Issue with cancan

I have created an app which uses devise and cancan for authentication and authorization . Using cancan I have defined two roles admin and operator. The admin can manage all and the operator can edit all but not destroy and the third is a normal user who can create and manage. But the code goes only to the default else block. This is my ability class and index.html

class Ability
include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user

    if user.role? :admin
      can :manage, :all
    elsif user.role? :operator
      can :read, :all
    else
      can :read, :all
    end
  end
end

index.html

  <h1>Listing todos</h1>

<table>
  <tr>
    <th>Name</th>
    <th>Description</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @todos.each do |todo| %>
  <tr>
    <td><%= todo.name %></td>
    <td><%= todo.description %></td>
    <% if can? :show, @todo %>
    <td><%= link_to 'Show', todo %></td>
     <% end %>
      <% if can? :update, @todo %>
    <td><%= link_to 'Edit', edit_todo_path(todo) %></td>
     <% end %>
      <% if can? :destroy, @todo %>
    <td><%= link_to 'Destroy', todo, :confirm => 'Are you sure?', :method => :delete %></td>
    <% end %>  
</tr>
<% end %>
</table>

<br />
<% if can? :destroy, @todo %>
<%= link_to 'New Todo', new_todo_path %>
<% end %>

Upvotes: 0

Views: 89

Answers (1)

klaffenboeck
klaffenboeck

Reputation: 6377

According to your momentarily setup, your operater-permissions and your default-permissions are the same. They only have the right to read all Models, not to edit them.

if user.role? :admin
  can :manage, :all
elsif user.role? :operator
  can :read, :all # no managing-abilities defined here
else
  can :read, :all # same abilities as operator
end

So, in case that your role?-method works correctly, your problem is not, that only the else-block gets triggered, but the operator is lacking abilities.

Upvotes: 1

Related Questions