The Making of That Nutty Guy: Page Layout

Free Ruby on Rails Tutorial

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

  1. 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.

  2. 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.

  3. Go to Applications > Utilities and launch Terminal.

  4. In Terminal, type cd and then a single space (do NOT hit Return yet).

  5. On the Desktop, open the Class Files folder, then drag the yourname-Rails Class folder and drop it on the Terminal window.

  6. In Terminal, hit Return to change into that directory.

  7. 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.

  8. As usual, Rails has created all our files. If you look in the yourname-Rails Class folder, you’ll see a new nutty folder.

  9. 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).

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Creating the Product Model, View, & Controller

The first thing we need to do is create our product model.

  1. 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.

  2. Switch the directory to nutty by typing the following into Terminal:

    cd nutty
    
  3. 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
  4. In your code editor, open nutty > db > migrate > #_create_products.rb

    NOTE: The number in the filename is a timestamp and will vary.

  5. 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, while scale specifies the number of digits after the decimal point.

  6. Save the file, then close it.

  7. 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.

  8. 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.

  9. Open seeds.rb in your code editor.

  10. 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.

  11. In your code editor, open nutty > db > seeds.rb.

  12. Select all the code in the file and delete it.

  13. 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.

  14. Save the file, then close it.

  15. 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.

  16. 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.

  17. The next thing to do is get our routing set up. In your code editor, navigate into:
    nutty > config > routes.rb

  18. Select and delete all the commented out code so that all that is left in the file is:

    Rails.application.routes.draw do
    end
    
  19. Type the following shown in bold:

    Rails.application.routes.draw do
       resources :products, only: [:index, :show]
    
       root 'products#index'
    end
    
  20. Save the file, then close it.

  21. In Terminal, start the Rails server:

    rails s
    
  22. 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.

  23. In your code editor, open nutty > app > controllers > products_controller.rb

  24. 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.)

  25. 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
    
  26. Save the file, then close it.

  27. Create a new file.

  28. Save the file as index.html.erb into nutty > app > views > products.

  29. Create another new file.

  30. 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.

  31. 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.

  1. 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.).

  2. In your code editor, open nutty > app > views > layouts > application.html.erb

  3. 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>
    
  4. Create a new file.

  5. Hit Cmd–V to paste the copied code into it because we’ll need it later.

  6. In your code editor, go back to: yourname-Rails Class > that nutty guy snippets > That Nutty Guy HTML > index.html

  7. Select all the content and copy it.

  8. Switch back to application.html.erb.

  9. Select all the content and replace it by pasting the copied code from index.html.

  10. Go back to the file where you pasted the three lines of code. Select them, copy them, then close the file without saving.

  11. 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">
    
  12. 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'>
    
  13. Reverse the order of the stylesheet_link_tag and javascript_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'>
    
  14. 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>
    
  15. Save the file.

  16. 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
    
  17. Open app > JavaScript > packs > application.js in your code editor.

  18. After the existing require statements, add:

    require("jquery")
    
    import 'bootstrap'
    import './src/application.scss'
    
  19. Create a new folder at app > JavaScript > packs > src

  20. Enter this folder and create application.scss

  21. Open application.scss and add a single line:

    @import '~bootstrap/scss/bootstrap';
    
  22. 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
    
  23. Minimize (but don’t close) your code editor so you can see the Desktop.

  24. From the Desktop, navigate to: Class Files > yourname-Rails Class > that nutty guy snippets > That Nutty Guy HTML > css

  25. Copy normalize.min.css and main.css.

  26. Navigate to: Desktop > Class Files > yourname-Rails Class > nutty > app > assets > stylesheets

  27. Paste the CSS files. (You should end up with four in total.)

  28. 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

  29. Add normalize.min above require_tree:

    *= require 'normalize.min'
    *= require_tree .
    *= require_self
    */
    
  30. Save the file, then close it.

  31. 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

  1. Open a Finder window and go to: Desktop > Class Files > yourname-Rails Class > that nutty guy snippets > That Nutty Guy HTML > img

  2. Hit Cmd–C to copy the img folder.

  3. Go to: Desktop > Class Files > yourname-Rails Level Class > nutty > public

  4. 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.

  5. 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.

  6. In a Finder window, go to: Desktop > Class Files > yourname-Rails Class > that nutty guy snippets > That Nutty Guy HTML > fonts

  7. Hit Cmd–C to copy the fonts folder.

  8. Go to: Desktop > Class Files > yourname-Rails Class > nutty > public

  9. Hit Cmd–V to paste the fonts folder into the public folder.

  10. We need to make some minor modifications in our CSS. In your code editor, open: nutty > app > assets > stylesheets > main.css

  11. 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.

  12. 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.
  13. Enter the following (the Find and Replace labels may be named differently in your code editor):

    Find What: ../
    Replace With: /
  14. 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

  15. Save the file, then close it.

  16. Go back to your browser and reload: localhost:3000

    Finally, the main page design is in place with all its images!

  17. Leave your code editor and Terminal open to continue with them in the next exercise.

Noble Desktop Publishing Team

The Noble Desktop Publishing Team includes writers, editors, instructors, and industry experts who collaborate to publish up-to-date content on today's top skills and software. From career guides to software tutorials to introductory video courses, Noble aims to produce relevant learning resources for people interested in coding, design, data, marketing, and other in-demand professions.

More articles by Noble Desktop Publishing Team

How to Learn Coding

Master coding with hands-on training. Learning how to code in JavaScript, Python, and other popular languages can pave the way to a job in tech, such as web development, data science & analytics, or software engineering.

Yelp Facebook LinkedIn YouTube Twitter Instagram