How to allow only admin link to view

I am making my admin user using the Michael Hartl Rails 3 Tutorial . I do this, so my admin can only see Index.html. erb for all users. So, how can I only allow my admin user to view my link?

This is what is in my UserController:

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 am trying to change for Admin to see only:

 <% if signed_in? %>        
      <%= link_to "Users", users_path %>
 <% end %>
+3
source share
3 answers

Write a helper method for this to keep your views 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
+6
source

I use account_type as an attribute for the 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 %>
+1

If you use Devise , you can easily achieve this in a few lines:

1- Add the attribute adminto the development table:

and. You can add it with the migration $ rails generate migration add_admin_to_users admin:boolean. Now your migration will look like this:

  class AddAdminToUsers < ActiveRecord::Migration
    def change
      add_column :users, :admin, :boolean, :default => false
    end
  end

b. You can also add it to the device table before transferringt.boolean :admin, null: false, default: false

2- In your opinion, you can do this:

<%= link_to "Users", users_path if current_user.admin? %>

After adding a table admin?to Devise, it becomes an attribute similar to the emailothers. And it ends with a question mark ?, because it's a Boolean type.

0
source

All Articles