Skip to main content
March 23, 2026Noble Desktop Publishing Team/13 min read

The Making of That Nutty Guy: Dynamic Content

Building Dynamic Ruby on Rails Applications

Core Concepts Covered

Dynamic Content

Transform static HTML into dynamic pages using Rails ERB templates and database-driven content rendering.

Partial Rendering

Create reusable code components that can be conditionally displayed across different pages and layouts.

Data Validations

Implement model-level validations to ensure data integrity and proper application behavior.

Topics Covered in This Ruby on Rails Tutorial:

Adding Dynamic Data, Rendering a Partial, Validations

Exercise Overview

Now that we've established our foundation with HTML, CSS, and JavaScript, along with our static assets like images and fonts, we're ready to transform this static content into a dynamic, data-driven Rails application. This exercise will demonstrate how Rails brings your front-end to life by connecting it to your database models and implementing the MVC pattern effectively.

  1. If you completed the previous exercise, you can skip the following sidebar. We strongly recommend completing the previous exercise (B1) before starting this one, as it establishes the necessary foundation for dynamic functionality. If you haven't finished it, follow the setup instructions in the sidebar below.

    Prerequisites Required

    This exercise builds directly on Exercise B1. If you haven't completed the previous exercise, you'll need to clone the repository and checkout the B1 branch to get the proper starting point.

If You Did Not Complete the Previous Exercise (B1)

  1. Close any files you may have open in your code editor.
  2. Open the Finder and navigate to Class Files > yourname-Rails Class
  3. Open Terminal.
  4. Type cd and a single space (do NOT press Return yet).
  5. Drag the yourname-Rails Class folder from the Finder to the Terminal window and press ENTER.
  6. Run rm -rf nutty to delete your existing copy of the nutty site.
  7. Run Git clone https://bitbucket.org/Noble Desktop/nutty.Git to copy the That Nutty Guy Git repository.
  8. Type cd nutty to enter the new directory.
  9. Type Git checkout B1 to bring the site up to the end of the previous exercise.
  10. Run bundle to install any necessary gems.
  11. Run yarn install—check-files to install JavaScript dependencies.

Coding the Product Index Page

The first step in creating a dynamic product catalog is establishing proper routing between our index and individual product pages. We'll transform static HTML into dynamic Rails views that pull data from our Product model, creating a seamless user experience that scales with your product database.

  1. For this exercise, we'll continue working with the nutty folder located in Desktop > Class Files > yourname-Rails Class > nutty

    If you haven't already done so, we suggest opening the entire nutty folder in your code editor (most modern editors like VS Code, Sublime Text, and Atom support this workflow for better project navigation).

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

    We're about to extract the product-specific content from the application layout and move it to a dedicated product index view. This follows Rails conventions and improves maintainability by separating layout concerns from content-specific markup.

  3. You're going to select a substantial chunk of code (approximately lines 62–107) that contains our featured products section. Locate the beginning and end markers shown below:

    <div id="featured">
       <h2 class="category">Featured Gifts</h2>
       <hr>

    Code Omitted To Save Space

    <p class="gray-text">$24.99</p>
       <div>
    </div>

    When you're finished selecting, there should be exactly 2 closing </div> tags remaining in the layout.

  4. Once selected, cut (Cmd–X) the code to move it to the clipboard.

  5. In the space where the code was cut, add the Rails yield helper as shown in bold:

    <div class="container">
       <div id="main" role="main">
    
          <%= yield %>
    
       </div>
    </div>

    The yield method is where Rails will inject the content from your individual view templates, making this layout reusable across different pages.

  6. Save the file to preserve your layout changes.

  7. In your code editor, open: nutty > app > views > products > index.html.erb

  8. Hit Cmd–V to paste the code you previously cut. This product catalog markup will now only appear on the products index page, following the Rails convention of separating concerns.

  9. Save the file.

    Next, we'll make the product display truly dynamic by replacing the static HTML with Rails iteration over our Product model. This approach ensures that adding new products to your database automatically updates the front-end display.

  10. Select another substantial section of code (approximately lines 11–45) that represents the individual product cards. Locate these beginning and end markers:

    <div class="col-md-3 col-sm-4">
    <a href="#"><img src="img/product_images/finger-tentacles.jpg" ALT="Finger Tentacles"></a>
    <a href="#"><p class="product">Finger Tentacles</p></a>

    Code Omitted To Save Space

    <a href="#"><p class="product">Buddha Board</p></a>
       <p class="gray-text">$24.99</p>
    </div>
  11. Once selected, delete the static code—we'll replace it with dynamic Rails templating.

  12. Add the Rails iteration logic shown in bold:

    <div class="row">
       <% @products.each do |product| %>
    <div class="col-md-3 col-sm-4">
      <a href="product.html"><img class="" src="img/product_images/tinfoil-hat.jpg" ALT="Tinfoil Hat"></a>
      <a href="product.html"><p class="product">Tinfoil Hat</p></a>
      <p class="gray-text">$7.99</p>
    </div>
       <% end %>
    </div>

    This each loop will iterate through every product in the @products instance variable, generating a product card for each item in your database.

  13. Delete the static anchor tags shown in bold:

    <a href="product.html"><img id="bill" class="" src="img/product_images/tinfoil-hat.jpg" ALT="Tinfoil Hat"></a>
    <a href="product.html"><p class="product">Tinfoil Hat</p></a>
  14. Wrap the product content in a Rails link helper as shown in bold:

    <div class="col-md-3 col-sm-4 col-xs-12">
       <%= link_to product do %>
          <img class="" … ALT="Tinfoil Hat">
          <p class="product">Tinfoil Hat</p>
       <% end %>
       <p class="gray-text">$7.99</p>

    The link_to helper with the product object automatically generates the correct URL path to the individual product page using Rails routing conventions.

  15. Around line 10, replace the static title Tinfoil Hat with dynamic content:

    <p class="product"><%= product.title %></p>
  16. Around line 12, replace $7.99 with Rails' built-in currency formatting:

    <p class="gray-text"><%= number_to_currency product.price %></p>

    The number_to_currency helper automatically formats prices according to locale settings and handles decimal precision consistently.

  17. Save the file to implement your changes.

  18. In a browser, navigate to localhost:3000 (reload if you're already there).

    You'll notice we're still using the Tinfoil Hat placeholder image, but the dynamic content (product titles and prices) should now reflect your actual database content. This demonstrates how Rails seamlessly blends static assets with dynamic data.

  19. Try clicking on a product. You'll notice we still need to implement the individual product page content—that's our next step.

Code Organization Best Practice

Moving the product listing code from the layout to the products index view follows Rails convention of keeping page-specific content in appropriate view files rather than shared layouts.

Every time we have a product, we're going to print one of these divs.
This demonstrates the core concept of iterating over database records to generate dynamic HTML content in Rails applications.

Adding the Product Pages' Content

Now we'll create the individual product detail pages by transferring the static HTML template into our Rails show view and making it fully dynamic. This process demonstrates how to convert any static HTML prototype into a working Rails application.

  1. In your code editor, open Desktop > Class Files > yourname-Rails Level 2 Class > That Nutty Guy HTML > product.html

    This static HTML file serves as our design template—we'll extract the relevant markup and transform it into a dynamic Rails view.

  2. We'll be selecting a substantial chunk of code (approximately lines 54–146) that contains the complete product detail layout. Locate these beginning and end markers:

    <div id="main" role="main">
    <div class="row">
       <div class="col-xs-12 hidden-sm hidden-xs">
          <ol class="breadcrumb">

    Code Omitted To Save Space

    </div>
       </div>
    </div>
    </div>
  3. Once selected, copy (Cmd–C) the code to transfer the template markup.

  4. Close the HTML file—we no longer need it open.

  5. Open nutty > app > views > products > show.html.erb

  6. Paste the code (Cmd–V) into the Rails view template.

  7. Save the file to preserve the template structure.

  8. Reload the product page in your browser. (If you closed it, navigate to localhost:3000 and click on any product.)

    Excellent! You now have a complete product detail page. However, you'll notice the product image link is broken—we need to correct the asset path for Rails' asset pipeline.

  9. Switch back to show.html.erb in your code editor.

  10. Around line 17, fix the image path by adding a leading slash as shown in bold:

    <img class="product" src="/img/product_images/tinfoil-hat.jpg" ALT="Tinfoil Hat">

    The leading slash ensures the browser looks for images relative to the domain root, not the current page URL.

  11. Reload the product page in your browser to verify the image displays correctly.

    Perfect! The image now loads properly. Currently, all product pages display identical content—let's implement dynamic data binding to make each product page unique.

  12. Return to show.html.erb in your code editor. We'll systematically replace static content with dynamic Rails expressions that pull data from the current product record.

  13. Access your editor's Find and Replace function:

    • If using Sublime Text: Go to Find > Replace
    • If using Dreamweaver: Go to Edit > Find and Replace
    • If using VS Code: Press Cmd+Option+F (Mac) or Ctrl+H (Windows)
  14. Replace all instances of the product name:

    Find What: Tinfoil Hat
    Replace With: <%= @product.title %>
  15. Click the Replace All button to update all instances throughout the template.

  16. Now replace the SKU/Item numbers with dynamic data:

    Find What: NG45636
    Replace With: <%= @product.sku %>
  17. Click the Replace All button to update the SKU references.

  18. Around line 23, locate the price element and replace the static value:

    <p class="price">$7.99</p>

    Replace with Rails' currency formatting helper:

    <p class="price"><%= number_to_currency @product.price %></p>
  19. Around line 40, find the product description section and replace the static content:

    <div class="tab-pane fade show active" id="details" role="tabpanel" aria-labelledby="home-tab">
       <p>Preserve free thought! Protect your mind from dangerous radio waves and other highly-suspect technologies used by suspicious government mind-control programs. Made from durable tin with a comfortable interior lining. Does not protect against visual mind-control tech such as subliminal messages in TV and advertising. You'll need goggles for that.</p>
    </div>

    Replace with dynamic content using Rails' text formatting helper:

    <div class="tab-pane fade show active" id="details" role="tabpanel" aria-labelledby="home-tab">
       <%= simple_format @product.description %>
    </div> <!-- /details -->

    The simple_format helper automatically converts line breaks to HTML paragraph tags, maintaining formatting from your database content.

  20. Around lines 43–49, replace the static specifications with dynamic content:

    <div class="tab-pane fade" id="specs" role="tabpanel" aria-labelledby="specs-tab">
        <ul>
          <li>Made from tin, not aluminum! Don't trust the knockoffs.</li>
          <li>Comfortable interior lining for extended wear.</li>
          <li>Guaranteed to protect your mind from bad influences.</li>
          <li>Secure chin strap.</li>
          <li>Adjustable band for any size head.</li>
        </ul>
      </div>

    Replace with the dynamic specifications field:

    <div class="tab-pane fade" id="specs" role="tabpanel" aria-labelledby="specs-tab">
       <%= @product.specs %>
    </div> <!-- /#specs -->
  21. For the reviews section (around lines 46–82), we'll implement a placeholder for future functionality. Select this large block of static review content:

    <div class="tab-pane fade" id="reviews" role="tabpanel" aria-labelledby="reviews-tab">
       <article>
          <div class="row">
             <div class="col-xs-12">
                <h3>Overall Rating:</h3>

    Code Omitted To Save Space

    <p>I bought this for my brother and he got such a kick out of it! The back of the box is also hilarious! I totally recommend this to anyone looking for a great gag gift!</p>
             </div>
          </div>
       </article>
       <hr>
    </div>

    Replace with a placeholder that anticipates future review functionality:

    <div class="tab-pane fade" id="reviews" role="tabpanel" aria-labelledby="reviews-tab">
       Coming Soon!
    </div>

    This approach maintains the interface structure while signaling to users that reviews are a planned feature.

  22. Save the file to implement all dynamic content changes.

  23. Return to the browser and navigate to localhost:3000. Click on different products to verify that each now displays its unique data—titles, prices, descriptions, and specifications should all reflect the individual product's database content.

    The breadcrumb navigation links may still point to placeholder URLs—let's fix those next.

Dynamic Content Replacement

0/4

Fixing the Home Links

Proper navigation is crucial for user experience and SEO. We'll update all the static links to use Rails' routing system, ensuring consistent and maintainable URLs throughout the application.

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

    We'll start by fixing the homepage links in the main layout file, which affects navigation across all pages.

  2. Access your editor's Find and Replace function:

    • If using Sublime Text: Go to Find > Replace
    • If using Dreamweaver: Go to Edit > Find and Replace
    • If using VS Code: Press Cmd+Option+F (Mac) or Ctrl+H (Windows)
  3. Replace all references to the static homepage:

    Find What: index.html
    Replace With: /

    Using a single forward slash creates links to the application root, which Rails automatically routes to your products index.

  4. Click the Replace All button to update all homepage references.

  5. Save the file to preserve the navigation updates.

  6. In your code editor, open nutty > app > views > products > show.html.erb

  7. Repeat the same Find and Replace operation for the product detail pages:

    Find What: index.html
    Replace With: /
  8. Click the Replace All button.

  9. Save the file to implement the navigation fixes.

  10. Reload any product page in the browser. Test the navigation by clicking on the logo in the top left corner—it should now smoothly return you to the homepage, demonstrating proper Rails routing in action.

Link Path Correction

Replacing static HTML file references with root path (/) ensures navigation works properly in the Rails routing system rather than looking for physical HTML files.

Specifying Where the Banner Appears

Effective UI design requires contextual awareness—certain elements should appear only where they're most relevant. We'll implement a conditional banner system using Rails partials and controller logic, demonstrating how to create flexible, reusable components.

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

    The "Ready to get Nutty?" banner currently appears on every page. For better user experience, it should only display on the main product index page where it serves as an effective call-to-action.

  2. Locate and select the banner section (around lines 52–58):

    <div class="jumbotron">
       <div class="container">
          <h1>Ready to get <span id="nutty"> Nutty?</span></h1>
          <p>Find clever, witty, and hilarious gifts for That Nutty Guy you know. 
          Guaranteed to make your friends and family smile.</p>
          <p><span id="gift-icon" class="ir"></span><a href="#">Try out our Gift 
          Finder</a></p>
       </div>
    </div>
  3. Cut the selected code (Cmd–X) to move it to a reusable partial.

  4. Replace the cut code with a conditional partial render:

    <%= render 'shared/get_nutty' if @get_nutty %>

    This code renders the get_nutty partial from the shared folder only when the @get_nutty instance variable is set to true. This approach gives controllers complete control over when the banner appears.

  5. Save the layout file.

  6. Create a new file in your code editor for the partial.

  7. Paste (Cmd–V) the banner code into the new file.

  8. Go to File > Save As. Navigate to nutty > app > views and create a new folder by clicking the New Folder button.

  9. Name the folder shared and click Create.

    The shared folder is a Rails convention for storing partials that might be used across multiple controllers or views.

  10. Navigate into the shared folder.

  11. Save the file as: _get_nutty.html.erb

    Important: Partial filenames must begin with an underscore (_), though you omit the underscore when referencing them in render statements. This Rails convention helps distinguish partials from full view templates.

  12. Return to nutty > app > views > layouts > application.html.erb

    Now we'll implement the conditional logic that determines when to display the banner.

  13. Verify that the conditional render statement is correctly positioned (around line 52):

    <%= render 'shared/get_nutty' if @get_nutty %>

    This Ruby expression only executes the render when @get_nutty evaluates to a truthy value.

  14. Save the layout file.

  15. Open: nutty > app > controllers > products_controller.rb

  16. Add the banner control variable to the index action:

    class ProductsController < ApplicationController
       def index
          @get_nutty = true
          @products = Product.all
       end

    Note: We're only setting @get_nutty = true in the index action, not in the show action. This means the banner will appear on the product catalog page but not on individual product detail pages.

  17. Save the controller file.

  18. In the browser, navigate to or reload localhost:3000. The banner should appear on the homepage as before. Click on any product—the banner should now be absent from product detail pages, creating a cleaner, more focused user experience.

    This implementation demonstrates Rails' flexibility in creating conditional UI elements that enhance rather than clutter the user interface.

Conditional Partial Rendering

1

Extract Banner to Partial

Move the jumbotron banner code into a reusable partial file in the shared views directory.

2

Add Conditional Logic

Use instance variable @get_nutty to control when the banner appears in the layout.

3

Set Controller Variable

Define @get_nutty = true only in the products index action to show banner on homepage.

Partial Naming Convention

Partial filenames always begin with an underscore, but when rendering them in ERB templates, you reference them without the underscore prefix.

Tweaking the Browser Window Titles

SEO and user experience both benefit from descriptive, contextual page titles. We'll implement dynamic title generation that reflects the current page content, improving both search engine optimization and browser tab management for users with multiple pages open.

  1. While in the browser, navigate to any product page.

  2. Examine the title in the browser window or tab. Currently, it displays "That Nutty Guy" for all pages. While this works for the index page, individual product pages should display the specific product name for better SEO and user orientation.

    Dynamic titles help users identify content when switching between browser tabs and provide search engines with more specific page information.

  3. Go back to your code editor and open the product controller file to implement dynamic title generation based on the current page context.

Dynamic Title Implementation

Controller Setup

Create @title instance variable in the show action to pass product-specific titles to the view layer.

Conditional Display

Use ERB conditional logic to show product name plus separator when @title exists, otherwise show default site name.

Key Takeaways

1Rails follows MVC architecture by separating page-specific content into appropriate view files rather than shared layouts
2ERB templates enable dynamic content rendering by embedding Ruby code within HTML using special tag syntax
3The each iterator allows you to loop through database records and generate repeated HTML structures for product listings
4Partial rendering promotes code reusability and conditional display of UI components across different pages
5Instance variables set in controllers become available in corresponding view templates for data display
6Rails helpers like number_to_currency and simple_format provide convenient formatting for common data types
7Model validations ensure data integrity by checking required fields and data types before database operations
8Find and replace operations across multiple files help efficiently convert static content to dynamic ERB templates

RELATED ARTICLES