Admin and Admin Page
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.
Enter the following two commands in your terminal:
rails generate migration AddAdminToUsers admin:boolean
rake db:migrate
The admin property can now be set from the rails console. Go ahead and set your user account to be an admin.
Start the Rails console and retrieve the user you want to modify (such as u1 = User.first
). You can use the toggle
command to toggle a property and save the change to the database:
u1.toggle(:admin)
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:
- Create a route
sold_out
that sends visits to theproducts
controller actionsold_out
. - Create a controller method
sold_out
in the products controller, and set the instance variable@title
in it to your desired title. - Create another instance variable
@products
and assign it all sold out products.
Add this line to routes.rb to create the route:
get 'sold_out', to: 'products#sold_out'
Add this method to products_controller.rb:
def sold_out
@title = "Sold Out Products"
end
Finally, create an instance variable in it that calls your model method sold_out:
@products = Product.sold_out
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.