0
votes

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 %>
1
More code would be helpful. The user_admin? method and the show method. You checked github.com/ryanb/cancan already? RegardsSG 86
I guess I have not finished setting everything up, I figured because if user.admin? worked in the ability.rb file, I could then use the line in other parts of the application to define if user_admin?thebusiness11

1 Answers

0
votes

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.