Admin and Admin Page


Collapse Content

Let's create an Admin user and code our own page for admins.

Creating an Admin

The simplest way to create an admin is to add a boolean admin column to users. Go ahead and do that.

Terminal Commands

The admin property can now be set from the rails console. Go ahead and set your user account to be an admin.

Console Commands

Custom Admin Page

Let's create a page for admins to view sold out products. Try to do all the following tasks without looking at the solution:

  1. Create a route sold_out that sends visits to the products controller action sold_out.
  2. Create a controller method sold_out in the products controller, and set the instance variable @title in it to your desired title.
  3. Create another instance variable @products and assign it all sold out products.
The Code

Rendering Different Views

Once we've coded the above, we'll need to render an actual view. We'll want to display a list of sold_out products with links for an admin to view. This is very similar to our index page of products, so it would be good if we could re-use the index template instead of creating a sold_out template. Fortunately we can!

By default, Rails renders the view template with the same name as the controller method. For example, the index method renders the template index.html.erb. However, Rails let's you override the default by explicitly declaring what file to render. To do this, call the Rails method render in your controller method and specify the file you want to render. In this case, render 'index' will render the index template. Here's the complete controller method:

def sold_out
  @title = "Sold Out Products"
  @products = Product.sold_out
  render 'index'
end

You can now open up /sold_out in your browser to view all your sold out products! If you don't have any sold_out products, change the quantity of one of your products to 0.

Q: How is calling render in the controller different from calling render in the view to render a partial?
A: It's a similar idea, but the controller renders an entire view template instead of a partial. In addition, a controller action can only render one template for each request, while you can render many partials in one view template.

See the Rails Guide on Layouts and Rendering for more info.

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