Reputation: 48503
Because the application I am working on will not have many administrators, I've added to the user
model a column admin for recognising if the respective user is admin or not.
In the controller, I would need to use ** before_filter :authenticate_admin!** filter, but this one is available only if in the application is model admin
.
How to add this filter if I use only the column attribute for admin, not the whole model? Testing
if current_user.try(:admin?)
# do something
end
in each action is not very practical.
Is there an inner filter for the variant when is used a column for the admin account?
Upvotes: 1
Views: 722
Reputation: 29174
You can create a custom filter
application_controller
def authorize_admin
if !current_user.admin?
redirect_to(root_path, :notice => "Not Allowed") and return
end
end
And use in your controller
before_filter :authenticate_user
before_filter :authorize_admin, :only => [:create]
Upvotes: 1
Reputation: 10053
For the actions which only admin can use, you can set a before filer to be executed. Say you want the access to be available for the below method only to admin
def create_new_users
User.create(name: "xxxx", email: "[email protected]")
end
use the below code in application_controller which checks for access for the method available only for admin. so use
before_filter :authenticate_user_access, :only => [:create_new_users]
def authenticate_user_access
current_user.is_admin
#is_admin the attribute in the user model to check for admin.set it false by default
end
You can add multiple methods in the :only which requires admin access.
Upvotes: 0