MVC: Views: Free Ruby on Rails Tutorial

Dive into the complexities of the Ruby on Rails framework with this extensive tutorial, covering topics such as creating a view, adding dynamic data, and rendering a partial, complete with step-by-step exercises to cement your learning.

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 a view, Adding dynamic data, Rendering a partial

Exercise Preview

preview mvc views

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

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.

Exercise Overview

In the last exercise, we looked at the basics of controllers and their role in routing requests, and now we’re going to look at what to do with the request once we receive it­—in other words, we are going to build some views.

  1. If you completed the previous exercises, you can skip the following sidebar. We recommend you finish the previous exercises before starting this one. If you haven’t finished them, do the following sidebar.

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

    1. Close any files you may have open.
    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 flix to delete your copy of the Flix site.
    7. Run git clone https://bitbucket.org/noble-desktop/flix.git to copy the Flix git repository.
    8. Type cd flix to enter the new directory.
    9. Type git checkout 3C 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.

Creating a View

We need to create a details page view for each movie. Before we do that, though, we’ll create the controller action that displays the view.

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

  2. Open 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. Make sure you’re in Terminal and hit Return to change into the new folder.

  6. Type the following to launch the server:

    rails server
    
  7. We suggest opening the flix folder in your code editor if it allows you to (like Sublime Text does).

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

  9. After the index method, add the following bold code to create a new show method and declare an instance variable:

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

    The show method looks very similar to the index method, except that instead of loading all movies, it loads a specific movie (using a parameter called id).

    We have to create a view before we go any further. You may be able to guess that this view is called show.html.erb. Our design department has made a great layout for the show page, which contains the details for each movie. All we need to do is implement the dynamic data that Rails is building for us into the design that has been given to us.

  10. Save the file.

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

  12. Copy all the code to the clipboard.

  13. Close the file.

  14. Create a new file in your code editor.

  15. Paste the code you just copied into the new file. (If you’re using Sublime Text, paste with Cmd–Shift–V to ensure proper indentation.)

  16. Save the file:
    • Into yourname-Rails Class > flix > app > views > movies
    • Name it show.html.erb
  17. Switch to the browser, navigate to localhost:3000 and notice that our page is still working correctly. Try mousing over the three featured movies, keeping an eye on the bottom left of the browser, where the URL link of each movie is displayed. Each of the movies is linking to a different detail page, such as localhost:3000/movies/1 and localhost:3000/movies/2

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

    Everything looks pretty good! There is lots of information about the movie and it’s nicely styled thanks to our designer.

  19. Click the Back button to go to the main movies page.

  20. Click on a different movie than you clicked before.

    Uh-oh! We’re getting information about Text M for Murder on every single page. This is because all we’ve done is simply copy the flat file that our designer gave us­—we haven’t put in any dynamic data yet.

    The site isn’t throwing any errors, but localhost:3000/movies/1, localhost:3000/movies/2, and localhost:3000/movies/3 all have the exact same information. Let’s put in the dynamic data so each detail page displays its unique info.

Adding Dynamic Data

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

    You might be wondering: How can we know what variables are in the model? Which ones do we have at our disposal? Rails gives you a really easy helper for working with that: it’s called debug. We can just tell Rails to debug the @movie instance variable, and simply dump the output onto the screen to find out what variables are available.

  2. Add the following bold code on its own line above the HTML (so it’s the first line of code in the file):

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

    You should recognize this as an embedded Ruby tag, indicated by the <% %> opening and closing tags. Here we include the = (equals sign) because we want to print the information to the screen. In the absence of the equals sign, the information in the tag is not printed to the screen.

  3. Save the file.

  4. Switch to the browser and go to localhost:3000/movies/1

    Thanks to the line of code we just wrote, there is some really rich information at the top of the page that tells us all the variables we can use, which are simply the columns of the movie model. They include an id, a title, a description, a runtime, a poster_image, and more.

    The values (i.e., the title being set to Text M for Murder and runtime being set to 127) are particular to this one record, and come from the seed file that we used to populate the database with three sample entries. Take a moment to look over all of the debug information.

  5. Switch to show.html.erb in your code editor. Now that we’re aware of the variables, we don’t need the debug info cluttering up the page anymore.

  6. Delete the <%= debug @movie %> line of code that you just wrote.

    Let’s go ahead and start populating the template file with those values we saw printed to the screen with debug. Let’s start with an easy one, the title.

  7. Find the following code, around line 6:

    <h2>Text M for Murder</h2>
    
  8. Edit the code as follows:

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

    Again, we’ve included an = (equals sign) in our embedded Ruby tag (ERB) because we want the value to print to the screen.

  9. Save the file.

  10. Switch to the browser and reload localhost:3000/movies/1. Notice that the title looks exactly like it did before; it still says Text M for Murder. This is a good sign, at least we didn’t break anything!

  11. Navigate to localhost:3000/movies/2 and localhost:3000/movies/3 and take a look at the titles. Each movie page now has its own individual title! This is exactly what we want.

  12. Because the embedded Ruby tags are behaving correctly, we can go ahead and add more to our code. Return to show.html.erb and make the following changes shown in bold. (NOTE: You’ll replace the two paragraphs with the description):

       <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. Add the rest of the dynamic data as shown below:

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

    Notice the question mark at the end of @movie.has_subtitles? which indicates that it will return a true/false value.

  14. Save the file.

  15. Switch to the browser and load localhost:3000/movies/1 to see how it’s looking. Check out localhost:3000/movies/2 and localhost:3000/movies/3 to see that each page is displaying the unique information of each entry.

    Unfortunately the layout is looking pretty rough. The description should be in two paragraphs, the Play Trailer button should be on its own line, and the date and ticket price (in the sidebar on the right of the page) are formatted incorrectly. Even more pressing—we still haven’t worked on the unique image for each movie page.

  16. Before we figure out how to deal with the images, let’s take a quick look at their location in relation to the other site files. In the Finder, navigate to flix > app > assets > images > posters

    Notice that the designer has provided two sub-folders with large posters for the detail pages and thumbs (thumbnail images) for the index page.

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

  18. Find the following area of the code at the very 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 <img> tag with the following bold code (type it all on one 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">
    

    Using a hashtag followed by braces: #{...} tells Rails that we are embedding a bit of Ruby code within the HTML. Also note that we’ve preserved the two image-related CSS classes that the designer created, imgLeft and poster-image. We’re also including alt text identifying the movie by title to keep the site accessible for users with screen readers.

  20. Save the file.

  21. Switch to the browser and reload the following pages:
    • localhost:3000/movies/1
    • localhost:3000/movies/2
    • localhost:3000/movies/3

    The images are looking good, and the proper images are being displayed on the proper pages! Let’s clean up more of the formatting with Rails helper methods.

  22. Switch to show.html.erb in your code editor and add the following helper method shown in bold:

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

    What the simple_format helper does (as you might remember from the Scaffolding exercise) is take a piece of text and apply very basic HTML styling to it, such as turning line breaks into <p> tags.

  23. Save the file.

  24. Switch to the browser and reload localhost:3000/movies/1 to see that the simple_format helper has successfully turned the description into two paragraphs, just like we hoped it would.

    Let’s work on formatting the subtitles area next. Currently it is displaying Subtitles: false, which is really more of a “computer” thing to say; it’s not very friendly or very human. It would be better if it said yes/no instead of true/false.

  25. Switch to show.html.erb in your code editor.

  26. We are about to write an if/else statement. In preparation for that, delete the = (equals sign) after the initial ERB tag so your line looks as shown in bold below:

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

    We did this because we don’t want to print the value of has_subtitles anymore; rather, we want to keep it hidden and examine it with the if/else statement.

  27. Make the following changes shown in bold to add the if/else statement:

    <div>
       <span>Subtitles:</span>
       <% if @movie.has_subtitles? %>   
          Yes
       <% else %>
          No
       <% end %>
    </div>
    
  28. Save the file.

  29. Switch to the browser and reload localhost:3000/movies/1 or any of the other movie detail pages to see that the change is working like we wanted it to. (If you get an error message, double-check that you deleted the = equals sign.)

    So far, so good! Let’s work on the ticket price. We want it to display a dollar sign at the beginning of the price and two values after the decimal point; it should say something like $12.50 instead of the current format (12.5). Luckily, Rails provides the perfect helper for this situation.

  30. Switch to show.html.erb in your code editor.

  31. Make the following change shown in bold:

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

    By default, the number_to_currency helper defaults to USD, but if you need it to be in Euros or rubles, there are config options for that within Rails.

  32. Save the file.

  33. Switch to the browser and reload localhost:3000/movies/1 or any of the other movie detail pages to see that the ticket price is now formatted correctly. However, we do need to fix the formatting of the date.

  34. Switch to show.html.erb in your code editor.

  35. Add the following bold code:

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

    Ruby and Rails make many things very easy, like the number_to_currency helper we implemented a few steps previously. However, dates are not quite as easy to fix because there are so many different ways of formatting them that vary between countries and situations.

    The code you just typed in parentheses stands for month (with no zero-padding), day (with no zero-padding), and the four-digit year.

    This code is challenging to remember, but it’s easily accessible at apidock.com/ruby/DateTime/strftime which has a ton of information about formatting dates and times. You can create any kind of date formatting you want using the info on this page, so it’s a good one to bookmark.

  36. Save the file.

  37. Switch to the browser and reload localhost:3000/movies/1 or any of the other movie detail pages to see that the date is now displaying properly! Great, all of the formatting issues on the detail pages have been resolved.

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