Skip to main content
April 1, 2026Noble Desktop Publishing Team/10 min read

MVC: Views: Free Ruby on Rails Tutorial

Master Ruby on Rails Views and Dynamic Data

Core MVC Components in Rails

Model

Handles data logic and database interactions. Defines the structure and behavior of your application's data entities.

View

Manages presentation layer and user interface. Renders HTML templates with embedded Ruby code for dynamic content.

Controller

Coordinates between models and views. Processes requests, handles routing, and prepares data for presentation.

Topics Covered in This Ruby on Rails Tutorial:

Creating a View, Adding Dynamic Data, Rendering a Partial

Exercise Preview

preview mvc views

Photo courtesy of istockphoto, © Korhan Karacan, Image #15095805

Exercise Overview

In the previous exercise, we explored the fundamentals of controllers and their critical role in routing requests within the Rails ecosystem. Now we'll tackle the next essential piece of the MVC puzzle: transforming those routed requests into meaningful user interfaces through views. This exercise will demonstrate how Rails seamlessly connects your data layer to compelling front-end experiences, a skill that remains central to modern web development in 2026.

  1. If you completed the previous exercises successfully, you can skip the following sidebar. We strongly recommend finishing exercises 3A–3C before proceeding, as they establish the foundational controller architecture we'll build upon. If you haven't completed them, follow the setup instructions below.

    Prerequisites Check

    This tutorial builds upon exercises 3A-3C covering Rails controllers and routing fundamentals. Complete setup instructions are provided for those who need to catch up.

If You Did Not Do the Previous Exercises (3A–3C)

  1. Close any files you may have open in your editor.
  2. Open the Finder and navigate to Class Files > yourname-Rails Class
  3. Launch 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 flix to remove your existing copy of the Flix application.
  7. Run Git clone https://bitbucket.org/Noble Desktop/flix.Git to clone the Flix repository fresh.
  8. Type cd flix to navigate into the project directory.
  9. Type Git checkout 3C to sync your codebase to the end state of the previous exercise.
  10. Run bundle to install all required Ruby gems and dependencies.
  11. Run yarn install—check-files to install JavaScript dependencies and ensure asset compilation works properly.

Quick Setup Process

1

Navigate to Project Directory

Open Terminal and use cd command with drag-and-drop folder method for accurate path navigation

2

Clone Repository

Remove existing flix directory and clone fresh copy from Git repository using provided commands

3

Install Dependencies

Run bundle and yarn install commands to ensure all gems and JavaScript dependencies are properly configured

Creating a View

Our next objective is building individual movie detail pages that showcase rich information about each film in our database. This pattern—creating dedicated views for individual resources—is fundamental to RESTful web applications and something you'll implement countless times in production environments. Before crafting the view template, we'll establish the controller action that orchestrates the data retrieval and rendering process.

  1. Open the Finder and navigate to Class Files > yourname-Rails Class

  2. Launch Terminal.

  3. Type cd and a single space (do NOT press Return yet).

  4. Drag the flix folder from the Finder to the Terminal window.

  5. Ensure Terminal is the active application and hit Return to change directories.

  6. Launch the Rails development server with the following command:

    rails server
  7. We recommend opening the entire flix project folder in your code editor for efficient file navigation and project overview.

  8. In your code editor, open flix > app > controllers > movies_controller.rb.

  9. After the existing index method, add the following code to create a new show method with its associated instance variable:

    def index
          @movies = Movie.all
       end
    
       def show
          @movie = Movie.find(params[:id])
       end
    end

    The show method follows Rails' RESTful conventions while demonstrating a crucial difference from our index action. Instead of retrieving all movies from the database, it loads a specific movie record using the id parameter from the URL. This parameter is automatically extracted from routes like /movies/1 or /movies/42, making it accessible through Rails' params hash—a cornerstone of dynamic web application behavior.

    Now we must create the corresponding view template to display this data. Following Rails' convention over configuration philosophy, this view will be named show.html.erb and placed in the movies views directory. Our design team has crafted an elegant layout for movie detail pages, and our task is to integrate Rails' dynamic data capabilities into their static design.

  10. Save the controller file.

  11. In your code editor, open yourname-Rails Class > flix snippets > show.html.

  12. Select all content and copy it to your clipboard.

  13. Close the snippet file.

  14. Create a new file in your code editor.

  15. Paste the copied code into the new file. (If using Sublime Text, use Cmd–Shift–V for paste with proper indentation preservation.)

  16. Save the file with these specifications:
    • Location: yourname-Rails Class > flix > app > views > movies
    • Filename: show.html.erb
  17. Switch to your browser and navigate to localhost:3000 to verify our existing functionality remains intact. Hover over the three featured movies while observing the status bar in your browser's bottom-left corner. Each movie now links to its unique detail page: localhost:3000/movies/1, localhost:3000/movies/2, etc.

  18. Click on Text M for Murder to view the detail page.

    The layout looks professionally styled and contains comprehensive movie information, thanks to our design team's excellent work.

  19. Click the browser's Back button to return to the main movies index.

  20. Click on a different movie to test the routing.

    Here we encounter our first issue: every detail page displays identical information about Text M for Murder, regardless of the URL. This occurs because we're serving static HTML content rather than dynamic, database-driven content. While Rails isn't throwing errors—which indicates our routing and basic MVC structure are working correctly—pages like localhost:3000/movies/1, localhost:3000/movies/2, and localhost:3000/movies/3 all show the same hardcoded information. Let's implement dynamic data binding to make each page unique.

def show @movie = Movie.find(params[:id]) end
The show method loads a specific movie using the id parameter, unlike the index method which loads all movies. This demonstrates Rails' RESTful routing conventions.
Rails Naming Conventions

View files follow a strict naming pattern: action_name.html.erb. The show action corresponds to show.html.erb in the movies views directory.

Adding Dynamic Data

The transition from static templates to dynamic, data-driven views represents one of the most powerful aspects of modern web frameworks. Rails provides several elegant tools for this transformation, including helpful debugging utilities that professional developers rely on daily.

  1. Return to show.html.erb in your code editor.

    Before diving into data integration, we need to understand what information our model provides. Rails includes a powerful debug helper that allows developers to inspect objects and their available attributes in real-time—an invaluable tool for both learning and professional debugging scenarios.

  2. Add the following code as the first line of your file, above all existing HTML:

    <%= debug @movie %>
    <div id="movie-info" class="clearfix">

    This embedded Ruby (ERB) tag demonstrates a key distinction in Rails templating. The <%= %> syntax includes an equals sign, which tells Rails to evaluate the Ruby code and output the result to the HTML. Without the equals sign, <% %> tags execute code silently without rendering output—perfect for control structures like loops and conditionals.

  3. Save the file.

  4. Switch to your browser and navigate to localhost:3000/movies/1

    The debug output reveals the complete structure of our movie object, displaying all available database columns as key-value pairs. You'll see attributes like id, title, description, runtime, poster_image, and others. These correspond directly to the database schema we established earlier. The specific values (such as the title "Text M for Murder" and runtime "127") come from our seed file that populated the database with sample data. Take a moment to examine this debug information—understanding your data structure is crucial for effective development.

  5. Return to show.html.erb in your code editor. With our data structure mapped out, we can remove the debug helper to clean up our view.

  6. Delete the <%= debug @movie %> line.

    Now we'll systematically replace static content with dynamic database values. Let's start with the movie title—a straightforward substitution that will demonstrate the core concept.

  7. Locate this code around line 6:

    <h2>Text M for Murder</h2>
  8. Replace it with dynamic content:

    <h2><%= @movie.title %></h2>

    This ERB tag accesses the title attribute of our @movie instance variable, demonstrating Rails' intuitive object-attribute syntax.

  9. Save the file.

  10. Switch to your browser and reload localhost:3000/movies/1. The title should appear unchanged—still showing "Text M for Murder"—which confirms our code is working correctly without breaking existing functionality.

  11. Navigate to localhost:3000/movies/2 and localhost:3000/movies/3 to observe the dynamic behavior. Each page now displays its unique title, demonstrating successful data binding.

  12. With our ERB implementation proven successful, let's expand our dynamic content. Return to show.html.erb and implement the following changes, replacing the existing static content:

    <h2><%= @movie.title %></h2>
       <p class="mpaa-rating">Rating: <%= @movie.mpaa_rating %></p>
       <p class="runtime">Runtime: <%= @movie.runtime %> minutes</p>
       <%= @movie.description %>
       <a href="#" class="button">Play Trailer</a>
    </div>
  13. Continue adding dynamic data to the movie details section:

    <div class="details">
       <h4>Movie Details</h4>
       <div>
          <span>Subtitles:</span>
          <%= @movie.has_subtitles? %>
       </div>
       <div>
          <span>Ticket Price:</span>
          <%= @movie.ticket_price %>
       </div>
       <div>
          <span>Release Date:</span>
          <%= @movie.release_date %>
       </div> 
    </div>

    Note the question mark in @movie.has_subtitles?—this Ruby convention indicates a predicate method that returns a boolean value (true/false). This naming pattern helps developers quickly identify method behavior and expected return types.

  14. Save the file.

  15. Test your implementation by visiting localhost:3000/movies/1, localhost:3000/movies/2, and localhost:3000/movies/3 to confirm each page displays unique information.

    While our dynamic data is working correctly, the presentation needs refinement. The description should be formatted as proper paragraphs, the button requires better spacing, and both the date and ticket price need professional formatting. Most importantly, we haven't addressed the movie poster images yet.

  16. Before implementing image functionality, let's examine the asset structure our designers have created. In Finder, navigate to flix > app > assets > images > posters

    You'll find two strategically organized subdirectories: large contains high-resolution images for detail pages, while thumbs houses smaller thumbnail images optimized for the index page. This asset organization pattern is common in professional web applications, balancing image quality with performance considerations.

  17. Return to show.html.erb in your code editor.

  18. Find the static image tag at the top of the document:

    <div id="movie-info" class="clearfix">
       <img class="imgLeft poster-image" src="/assets/posters/large/textmformurder-2x.jpg">
    
       <div class="overview">
  19. Replace the static <img> tag with Rails' dynamic image helper (enter as a single line):

    <div id="movie-info" class="clearfix">
       <%= image_tag "posters/large/#{@movie.poster_image}", class: "imgLeft poster-image", ALT: "#{@movie.title} poster" %>
    
       <div class="overview">

    This code demonstrates several advanced Rails concepts. The #{...} syntax enables string interpolation, dynamically inserting Ruby expressions into strings. Rails' image_tag helper automatically handles asset pipeline integration while preserving the designer's CSS classes (imgLeft and poster-image). The dynamic ALT attribute ensures accessibility compliance by providing descriptive text for screen readers.

  20. Save the file.

  21. Test the image implementation across all movie pages:
    • localhost:3000/movies/1
    • localhost:3000/movies/2
    • localhost:3000/movies/3

    Each page should now display its corresponding poster image, confirming successful dynamic image rendering. Next, we'll enhance the formatting using Rails' built-in helper methods.

  22. Return to show.html.erb and implement the simple_format helper for better text presentation:

    <h2><%= @movie.title %></h2>
       <p class="mpaa-rating">Rating: <%= @movie.mpaa_rating %></p>
       <p class="runtime">Runtime: <%= @movie.runtime %> minutes</p>
       <%= simple_format @movie.description %>
       <a href="#" class="button">Play Trailer</a>
    </div>

    The simple_format helper intelligently converts plain text into properly formatted HTML, transforming line breaks into paragraph tags and handling basic text structure. This approach is particularly valuable when working with user-generated content or data imported from external sources.

  23. Save and test the formatting change at localhost:3000/movies/1. The description should now display as properly formatted paragraphs.

    Let's address the subtitles field, which currently displays "false"—technical but not user-friendly. Professional applications require human-readable output.

  24. In show.html.erb, modify the subtitles section by first removing the equals sign from the ERB tag:

    <div>
       <span>Subtitles:</span>
       <% @movie.has_subtitles? %>
    </div>

    We remove the equals sign because we'll be using conditional logic rather than directly outputting the boolean value.

  25. Implement a conditional statement to display user-friendly text:

    <div>
       <span>Subtitles:</span>
       <% if @movie.has_subtitles? %>   
          Yes
       <% else %>
          No
       <% end %>
    </div>
  26. Save and test the conditional logic at localhost:3000/movies/1. The subtitles field should now display "Yes" or "No" instead of boolean values.

    Now let's address the ticket price formatting. Professional applications require proper currency display, and Rails provides excellent helpers for this common need.

  27. In show.html.erb, implement the currency formatting helper:

    <div>
       <span>Ticket Price:</span>
       <%= number_to_currency @movie.ticket_price %>
    </div>

    The number_to_currency helper automatically formats numbers as currency with appropriate symbols and decimal places. While it defaults to USD formatting, it supports extensive internationalization options for global applications—a crucial consideration in today's market.

  28. Save and test the currency formatting improvement.

  29. Finally, let's address date formatting—often one of the more complex formatting challenges in web applications. Add the following code:

    <div>
       <span>Release Date:</span>
       <%= @movie.release_date.strftime('%-m/%-d/%Y') %>
    </div>

    Date formatting in Rails leverages Ruby's powerful strftime method. The format string %-m/%-d/%Y specifies month and day without zero-padding, plus a four-digit year. While this syntax can be challenging to memorize, resources like apidock.com/ruby/DateTime/strftime provide comprehensive references for any date format requirements you might encounter in professional development.

  30. Save the file and test the complete implementation across all movie detail pages.

    Excellent! You've successfully transformed a static HTML template into a fully dynamic, database-driven view that demonstrates professional-grade formatting and user experience considerations. This pattern of progressive enhancement—starting with static content and systematically adding dynamic functionality—is a proven approach in professional web development.

Rails Helper Methods for Data Formatting

debug

Displays all available instance variables and their values. Essential for development and understanding data structure.

simple_format

Converts plain text to HTML with basic formatting. Transforms line breaks into paragraph tags automatically.

number_to_currency

Formats numerical values as currency with proper symbols and decimal places. Defaults to USD format.

image_tag

Generates HTML img tags with Rails asset pipeline integration. Supports CSS classes and accessibility attributes.

Static vs Dynamic Content Implementation

FeatureStatic HTMLDynamic ERB
Title Display<h2>Text M for Murder</h2><h2><%= @movie.title %></h2>
Image Sourcesrc="/assets/posters/large/textmformurder-2x.jpg"<%= image_tag "posters/large/#{@movie.poster_image}" %>
Price Format12.5<%= number_to_currency @movie.ticket_price %>
Recommended: Dynamic ERB templates provide flexibility and maintainability for database-driven content
ERB Tag Syntax

Remember the difference: <%= %> prints output to screen, while <% %> executes code without output. This distinction is crucial for conditional statements and loops.

Dynamic Data Implementation Checklist

0/5
Date Formatting Resource

Ruby date formatting can be complex. Bookmark apidock.com/ruby/DateTime/strftime for comprehensive formatting options and examples.

Key Takeaways

1Rails views use ERB (Embedded Ruby) templates to combine HTML with dynamic Ruby code for database-driven content
2The show action in controllers loads specific records using params[:id], following RESTful routing conventions
3Rails helper methods like number_to_currency, simple_format, and image_tag provide built-in formatting and presentation tools
4ERB syntax distinguishes between <%= %> for output and <% %> for execution-only code, essential for conditional logic
5The debug helper method reveals all available instance variables and their values, crucial for development and troubleshooting
6Rails naming conventions require view files to match controller actions (show.html.erb for show action)
7Dynamic image rendering with image_tag integrates with Rails asset pipeline and supports CSS classes and accessibility features
8String interpolation with #{} syntax allows embedding Ruby variables within HTML attributes and content

RELATED ARTICLES