Premium Content - Free Preview

We just created some pages for admins but currently anyone can access it and change the data, so let's fix that now!

Authentication is the process to verify who a user is, usually with a password. Authorization refers to the rules to determine what a user can do. For example, a regular user may get access to ordinary pages, while an admin will be able to access admin-only pages.

Let's set up authorization so non-admins cannot access admin-only pages. You could use a gem to handle authorization, but when the authorization rules are simple it's quicker to just code it yourself.

Redirecting users

When non-admins visit admin-only pages, we want to redirect them to the home page. Let's create a method for this purpose on the bottom of ProductsController:

class ProductsController < ApplicationController

  #...all controller actions...


   def ensure_admin!
     unless current_user.admin?
       redirect_to root_path


This code introduces a few new things, so let's break it down:

private - add this line to the bottom of a class to mark all methods below it as private. Private methods can only be accessed from within the class itself, not outside of it. The method we're about to create (ensure_admin!) is only for internal use of the controller, and is not for external code or requests.

current_user - Devise provides a helper method current_user which returns the current signed in user.

.admin? - this method checks if the user's admin value is true. It's equivalent to checking if current_user.admin == true.

redirect_to root_path - when the user is not an admin, we call the Rails method redirect to redirect the user to a different path, such as the home page in this case.

redirect_to vs. render
It's important to realize that redirect_to creates a new request for the page you're sending the person to, and doesn't save any instance @variables from your current code that you may have assigned.

Previously, you saw how render let's you render a different template. This only renders that template, but it doesn't run any code from the controller action with that name.

Controller Filters

Now that you have a method to ensure the user is an admin, it's time to use it. Rails let's you create controller filters to run code before or after a controller action. Use the Rails method before_action to run code before a controller action, and pass it the name of the method to execute. These filters are customarily placed at the top of the controller class:

End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Contact Us
Sign in or email us at [email protected]