Scott S.
Scott S.

Reputation: 759

Checking Ability in cancan

I'm a relative newbie and I'm trying to get cancan working in a simple project. I've followed the Railscast and have read the documentation, but I'm missing something.

There are 2 problems I'm having.

  1. I have the Edit/Create links correctly hiding for general users. But, they're also hidden for admin users.
  2. If I comment out the code for hiding the links above, when an admin user clicks on them they get an Access Denied message which should be displayed for non-admin users

So I think my problem is that the app isn't correctly checking abilities. I have checked the database and the role column is correctly populated with 'admin' for this user.

Here is my User model:

class User < ActiveRecord::Base
  has_secure_password

  #this is for authentication
  attr_accessible :email, :password, :password_confirmation, :role
  validates_uniqueness_of :email
  #end of authentication

 end

In my Instructors controller I have added "load_and_authorize_resource" to the top.

My Ability.rb file looks like this

class Ability
  include CanCan::Ability

  def initialize(user)
    # Define abilities for the passed in user here. For example:
    #
      user ||= User.new # guest user (not logged in)
      if user.admin?
        can :manage, :all
      else
        can :read, :all
      end
  end
end

My view where I'm hiding the controls based on role I have this code:

    <% if can? :manage, Instructor %>
<td><%= link_to 'Edit', edit_instructor_path(instructor) %></td>
<td><%= link_to 'Destroy', instructor, method: :delete, data: { confirm: 'Are you sure?' } %></td>
    <% end %>

All help is greatly appreciated.

Thanks

Scott

Upvotes: 0

Views: 273

Answers (2)

Scott S.
Scott S.

Reputation: 759

I changed:

if user.admin?

to

if user.id

And it worked perfectly

Upvotes: 0

Ben Downey
Ben Downey

Reputation: 2665

Instead of this

<% if can? :manage, Instructor %>

Try this

<% if user.has_role? :admin %>

(Assuming that in your app, admins manage/have more rights than instructors.)

Upvotes: 0

Related Questions