Explore the step-by-step tutorial on how to use Ruby on Rails to create an e-commerce site for "That Nutty Guy". Learn not only how to create product models, views, and controllers, but also how to incorporate the designer’s HTML/CSS, add Bootstrap 4 with Webpacker, and fix missing images and fonts.
Key Insights
- The tutorial provides a comprehensive guide on creating a product model, view, and controller in Ruby on Rails, as well as how to incorporate a designer's HTML/CSS into a Ruby on Rails application.
- Bootstrap 4 can be incorporated into Rails 6 using Webpacker and Yarn, providing a more interactive and responsive interface for the e-commerce site.
- The tutorial also covers how to navigate and use Terminal for creating and managing Rails applications, including commands such as 'cd', 'rails new', 'rails db:migrate', and 'rails db:seed'.
- It provides instructions on how to set up the site design using Bootstrap, jQuery, and popper.js, as well as how to fix missing images and fonts to improve the site's aesthetics.
- The step-by-step guide includes procedures for setting up routing, creating an index action, and assigning instance variables in Ruby on Rails, all of which are crucial for building the product pages of the e-commerce site.
- The tutorial emphasizes the importance of correct file naming and location in Rails, as mistakes in either can prevent the application from functioning properly.
Explore this comprehensive tutorial on Ruby on Rails that covers a variety of topics, including the creation of product models, views, and controllers, the incorporation of Bootstrap 4 with Webpacker, and solutions for missing images and fonts issues.
This exercise is excerpted from Noble Desktop’s past web development training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.
Topics covered in this Ruby on Rails tutorial:
Creating the product model, view, & controller, Incorporating the designer’s HTML/CSS, Adding Bootstrap 4 with Webpacker, Fixing the missing images & fonts
Exercise Overview
This next series of exercises will show you how the That Nutty Guy site that we start with in Exercise 8A was created. This will be a sort of refresher of what was covered in the first half of the book: how to create a model object, how to convert HTML designs into a Ruby on Rails application, how to work with controllers and views, routing, etc. As an added bonus, you’ll see how to incorporate Bootstrap into Rails 6 using Webpacker and Yarn.
Getting Started
In a browser, open the static HTML homepage our designer provided us: Desktop > Class Files > yourname-Rails Class > that nutty guy snippets > That Nutty Guy HTML > index.html.
This will be the front page of our ecommerce site. Click on Tinfoil Hat to see its detail page. In this exercise, we will build out the index and product pages.
Go to Applications > Utilities and launch Terminal.
In Terminal, type
cd
and then a single space (do NOT hit Return yet).On the Desktop, open the Class Files folder, then drag the yourname-Rails Class folder and drop it on the Terminal window.
In Terminal, hit Return to change into that directory.
-
Create the Rails application by typing:
rails new nutty
NOTE: Remember to hit Return after each line of code in Terminal unless we specifically say not to. We won’t remind you again.
As usual, Rails has created all our files. If you look in the yourname-Rails Class folder, you’ll see a new nutty folder.
We’ll be working with this new nutty folder. If you haven’t already done so, we suggest opening it in your code editor if it allows you to (like Sublime Text does).
Creating the Product Model, View, & Controller
The first thing we need to do is create our product model.
In a browser, open product.html (from That Nutty Guy HTML). This is a template for the product info page. For now, we’ll be building the Details and Specs tabs.
-
Switch the directory to nutty by typing the following into Terminal:
cd nutty
-
We need to generate a model. In Terminal, type the following (it is a single command, so press Return after typing the entire code shown here):
rails g model product title:string sku:string description:text specs:text price:decimal
This created a model file, a couple of test files, and a migration file in our database. To explain some of the syntax:
-
g
: generate -
product
: name of model -
title
,sku
,description
,specs
,price
: the fields we want to have in the initial model
-
-
In your code editor, open nutty > db > migrate > #
_
create_
products.rbNOTE: The number in the filename is a timestamp and will vary.
-
Around line 8, add the following code in bold (don’t miss the comma):
t.decimal :price, precision: 8, scale: 2
NOTE: Different databases have different defaults when it comes to how many decimal places are in a number. Some will even default to zero decimal places, in which case a price, for example, would be listed in whole dollars with no cents.
precision
specifies the total number of digits, whilescale
specifies the number of digits after the decimal point. Save the file, then close it.
-
Now that we’ve amended the migration, go to Terminal and run this command to populate the database and start building its structure:
rails db:migrate
Next we need to create a seeds file. A seeds file contains info about model objects on your website. You can run it at the command line and prepopulate a development instance of your site with sample data.
To save you some time, we’ve put the code in a file for you. In Finder, navigate to the Desktop > Class Files > yourname-Rails Level 2 Class > snippets folder.
Open seeds.rb in your code editor.
Select all the code and hit Cmd–C to copy it, then close the file. Rails automatically created a seeds.rb file, but we want to replace it with this custom code.
In your code editor, open nutty > db > seeds.rb.
Select all the code in the file and delete it.
-
Paste the new code.
If you take a look at the new code, you’ll see that it lists an array of products, each with their own attributes.
Save the file, then close it.
-
In Terminal, type:
rails db:seed
You should see that Terminal listed the eight products that were included with the site. They have been populated to the database by the previous command.
-
Now that we’ve got the products, it would be great to be able to see them. Type the following to create a products controller as well as supporting files for it:
rails g controller products
NOTE: Models are always singular, but controllers are always plural.
The next thing to do is get our routing set up. In your code editor, navigate into:
nutty > config > routes.rb-
Select and delete all the commented out code so that all that is left in the file is:
Rails.application.routes.draw do end
-
Type the following shown in bold:
Rails.application.routes.draw do resources :products, only: [:index, :show] root 'products#index' end
Save the file, then close it.
-
In Terminal, start the Rails server:
rails s
-
Open a browser and navigate to: localhost:3000
It should say, The action ‘index’ could not be found… which shows that our routing is working.
In your code editor, open nutty > app > controllers > products_controller.rb
-
Type the following shown in bold:
class ProductsController < ApplicationController def index @products = Product.all end end
Here, we’ve created an
index
action and assigned an instance variable called@products
that’s going to have all products in it. (NOTE: This is exactly what we did in section 3 to build the Flix site.) -
On the show page, we’ll load a specific product based on the id parameter. Type the code shown in bold:
class ProductsController < ApplicationController def index @products = Product.all end def show @product = Product.find(params[:id]) end end
Save the file, then close it.
Create a new file.
Save the file as index.html.erb into nutty > app > views > products.
Create another new file.
-
This time, save the file as show.html.erb into the same nutty > app > views > products folder.
We’ve created these files in this way because the correct naming and location of files is extremely important in Rails; things will not work if there is a mistake in either. The fact that these files are blank won’t matter.
-
Go to your browser and navigate to localhost:3000 (or reload the page if you’re already there).
The page will be blank, but notice there is no longer an error and now the name Nutty appears at the top of the browser window. This means that things are set up correctly.
Setting Up the Site Design
It’s time to put together the design for our site.
-
In your code editor, open the following file: Desktop > Class Files > yourname-Rails Class > that nutty guy snippets > That Nutty Guy HTML > index.html
The first thing we want to carve out of this is our page template. Remember that in Rails, we’re working with a templating system. Individual views are going to represent pieces of the application that are distinct to that particular controller action, where something is unique on that page.
We’ll start by setting up our main page layout, those pieces of the site that are fixed and don’t change (such as the header, footer, nav menu, etc.).
In your code editor, open nutty > app > views > layouts > application.html.erb
-
Copy (Cmd–C) the code shown in bold:
<head> <title>Nutty</title> <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %> </head>
Create a new file.
Hit Cmd–V to paste the copied code into it because we’ll need it later.
In your code editor, go back to: yourname-Rails Class > that nutty guy snippets > That Nutty Guy HTML > index.html
Select all the content and copy it.
Switch back to application.html.erb.
Select all the content and replace it by pasting the copied code from index.html.
Go back to the file where you pasted the three lines of code. Select them, copy them, then close the file without saving.
-
Go back to application.html.erb and select the following lines of code (around lines 11–12):
<link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/main.css">
-
Paste the embedded Ruby tags over them. You should end up with:
<meta name="viewport" content="width=device-width,initial-scale=1"> <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %> <link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
-
Reverse the order of the
stylesheet_link_tag
andjavascript_pack_tag
. This is necessary because we’ll be using JavaScript to package Bootstrap, and we need to load Bootstrap’s styles before our own.<meta name="viewport" content="width=device-width,initial-scale=1"> <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> <link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
-
Scroll down to the bottom of the code. Find the jQuery and JavaScript code around lines 145–148 and delete it:
</footer> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.1.min.js"><\/script>')</script> <script src="js/vendor/bootstrap.min.js"></script> </body>
Save the file.
-
These designs were built with Bootstrap 4. The right way to add these libraries is not directly to the HTML but with Webpacker. We need bootstrap, jQuery, and popper.js. Let’s add them with yarn:
yarn add bootstrap@4.3.1 jquery popper.js
Open app > JavaScript > packs > application.js in your code editor.
-
After the existing require statements, add:
require("jquery") import 'bootstrap' import './src/application.scss'
Create a new folder at app > JavaScript > packs > src
Enter this folder and create application.scss
-
Open application.scss and add a single line:
@import '~bootstrap/scss/bootstrap';
-
Open config > webpack > environment.js and update its contents as follows:
const { environment } = require('@rails/webpacker') const webpack = require('webpack') environment.plugins.append('Provide', new webpack.ProvidePlugin({ $: 'jquery/src/jquery', jQuery: 'jquery/src/jquery', Popper: ['popper.js', 'default'] })) module.exports = environment
Minimize (but don’t close) your code editor so you can see the Desktop.
From the Desktop, navigate to: Class Files > yourname-Rails Class > that nutty guy snippets > That Nutty Guy HTML > css
Copy normalize.min.css and main.css.
Navigate to: Desktop > Class Files > yourname-Rails Class > nutty > app > assets > stylesheets
Paste the CSS files. (You should end up with four in total.)
Just as we have application.html.erb, which is the global layout for our whole application, we have application.css, an app assets style sheet. In your code editor, open: nutty > app > assets > stylesheets > application.css
-
Add normalize.min above require_tree:
*= require 'normalize.min' *= require_tree . *= require_self */
Save the file, then close it.
In the browser, reload localhost:3000. As you can see, the site is improving, though it is still missing images and some of the fonts. We’ll fix that next.
Fixing the Missing Images & Fonts
Open a Finder window and go to: Desktop > Class Files > yourname-Rails Class > that nutty guy snippets > That Nutty Guy HTML > img
Hit Cmd–C to copy the img folder.
Go to: Desktop > Class Files > yourname-Rails Level Class > nutty > public
-
Hit Cmd–V to paste the img folder into the public folder.
NOTE: Anything in the img folder in the public folder is going to be at the root of the site.
-
Go back to your browser and reload: localhost:3000
Cool! The images are there! However, some things are still missing, like the font for the word Nutty. We need to copy over the fonts.
In a Finder window, go to: Desktop > Class Files > yourname-Rails Class > that nutty guy snippets > That Nutty Guy HTML > fonts
Hit Cmd–C to copy the fonts folder.
Go to: Desktop > Class Files > yourname-Rails Class > nutty > public
Hit Cmd–V to paste the fonts folder into the public folder.
We need to make some minor modifications in our CSS. In your code editor, open: nutty > app > assets > stylesheets > main.css
At the top of the code, notice the URLs pointing to the font files. They start with
..
in order to point to the previous folder. That was necessary for the HTML comps, but it no longer works in Rails. We need to delete every instance of them.-
Go to the following to do a Find and Replace:
- If you are using Sublime Text, go to Find > Replace.
- If you are using Dreamweaver, go to Edit > Find and Replace.
-
Enter the following (the Find and Replace labels may be named differently in your code editor):
Find What: ../
Replace With: /
-
Click the Replace All button. A total of 12 replacements should be made.
NOTE: Remember when files are in the public folder, it’s like they’re at the root of the site. For example, the img folder would be at: localhost:3000/img
Save the file, then close it.
-
Go back to your browser and reload: localhost:3000
Finally, the main page design is in place with all its images!
Leave your code editor and Terminal open to continue with them in the next exercise.