Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow only the admin to view link

I making my Admin User using Michael Hartl's Rails 3 Tutorial.I am making it so my admin user can only see the Index.html.erb for all users. So, How do I allow my link to be viewed by my admin user only?

This is whats in my UsersController:

before_filter :authenticate, :only => [:destroy,:index,:show,:edit, :update]
before_filter :correct_user, :only => [:edit, :update]
before_filter :admin_user,   :only => [:index,:destroy]
.
.
.
.
private
.
.
.       
def admin_user
    authenticate
    redirect_to(root_path) unless current_user.admin?
end 

This is what i'm trying to edit for Admin to see only:

 <% if signed_in? %>        
      <%= link_to "Users", users_path %>
 <% end %>
like image 210
LearningRoR Avatar asked Feb 25 '23 06:02

LearningRoR


2 Answers

Write a helper method for that so that your views are clean and readable.

your_view.html.erb

<% link_to "Users", users_path if admin? %>

helpers/application_helper.rb

def admin?
  @current_user.name == "Mr.Wallinzi"
  # I made up the line above. Implement your own checks according to your setup
end
like image 178
edgerunner Avatar answered Feb 26 '23 20:02

edgerunner


I use account_type as an attribute for a user. So I wrote something like

def is_admin
   return true if self.account_type == 1 #The admin account type
end

So...

<%if signed_in? && @active_user.is_admin %>      
  <%= link_to "Users", users_path %></div>
<% end %>
like image 24
Kyle Macey Avatar answered Feb 26 '23 19:02

Kyle Macey