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开发者_Go百科 => [: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 %>
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
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 %>
If you use Devise, you could easily achieve that in few lines:
1- Add admin
attribute to Devise table:
a. You can add it using migration: $ rails generate migration add_admin_to_users admin:boolean
. Your migration will now look like this:
class AddAdminToUsers < ActiveRecord::Migration
def change
add_column :users, :admin, :boolean, :default => false
end
end
b. Also you can add it to Device table before migration t.boolean :admin, null: false, default: false
2- In your view you can this so:
<%= link_to "Users", users_path if current_user.admin? %>
After you add admin?
to Devise table it becomes an attribute similar to email
and others. And it ends with question mark ?
because it's a boolean type.
精彩评论