thebusiness11
thebusiness11

Reputation: 521

Issues with Cancan and rails_admin with devise

So I have setup rails_admin with devise and cancan, I have it so that only admins can access the /admin pages.

But when trying to only show certain code to admins using <% if user_admin? %> I get undefined methoduser_admin?' for`

ability.rb

class Ability include CanCan::Ability

  def initialize(user)
      user ||= User.new # guest user (not logged in)
      if user.admin?
        can :manage, :all
        can :access, :rails_admin #grant access to rails_admin
        can :dashboard #gives access to the dashboard

      else
        can :read, :all
      end
  end
end

_header.html.erb

 <% if user_admin? %>
 <li><%= link_to 'Settings', edit_user_registration_path %></li>
 <li><%= link_to 'Logout', destroy_user_session_path, method: :delete %></li>
 <% else %>
 <li><%= link_to "Create Account", new_user_registration_path %></li>
 <li><%= link_to "Login", new_user_session_path %></li>
 <% end %>

Upvotes: 0

Views: 1064

Answers (1)

thebusiness11
thebusiness11

Reputation: 521

I needed to set the abilities up in the ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
      user ||= User.new # guest user (not logged in)
      if user.admin?
        can :manage, :all
        can :access, :rails_admin #grant access to rails_admin
        can :dashboard #gives access to the dashboard

      else
        can :read, :all
      end
  end
end

Then was able to just call

  <% if can? :access, :rails_admin %>
  <li><%= link_to 'Admin', rails_admin_path %></li>
  <% end %>

I can now do if can? on anything I want to authorize.

Upvotes: 0

Related Questions