0

所以我用 devise 和 cancan 设置了 rails_admin,我有它,所以只有管理员可以访问 /admin 页面。

但是当试图只向管理员显示某些代码时,<% if user_admin? %>我得到undefined method了 user_admin?为`

能力.rb

类能力包括 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 %>
4

1 回答 1

0

我需要在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

然后就可以打电话了

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

如果可以,我现在可以做什么?我想授权的任何事情。

于 2012-12-01T00:28:02.810 回答