开发者

AuthLogic admin user & hide admin links for non-admins

开发者 https://www.devze.com 2023-02-07 22:27 出处:网络
How do have an admin user and how do I hide hype开发者_JAVA百科rlinks for non-admin users?An alternative approach that I use regularly is to have another model called UserGroup.For example:

How do have an admin user and how do I hide hype开发者_JAVA百科rlinks for non-admin users?


An alternative approach that I use regularly is to have another model called UserGroup. For example:

$ rails g scaffold user_group name:string description:text is_admin:boolean

You would then add a user_group_id:integer to your user model:

$ rails g migration add_user_group_id_to_users user_group_id:integer

In your user model, you could then add two instance methods to help you figure out if any specific user is a "normal" user or an "admin" user:

#app/models/user.rb
def normal?
  self.user_group && !self.user_group.is_admin
end

def admin?
  self.user_group && self.user_group.is_admin
end

This is probably over-kill for projects where there are only admins and non-admins, but is handy if you have many categories of users, such as ecommerce_manager, story_editor, etc.


I looked long and hard to find out how to do this, in the end it was too simple! I didn't need route changes, loads of controller code or anything like that. Just add a field in the database called admin_flag through a migration), then modify the Rails view form for new/edit to use it. Then on the application/html.erb just add:

  <% if current_user %>
      <% if current_user.admin_flag == true %>
      | <%=link_to(:categories, :categories) %>
      | <%=link_to(:users, :users) %>
      <% end %>
  <% end %>

This will only show users and categories if the user logged in is admin too. Do this after setting at least one admin user or you will need to use sql to set at least 1 admin user.

0

精彩评论

暂无评论...
验证码 换一张
取 消