AI Reading
Quick summary of this article
This chapter walks through building a simple welcome page in Rails, demonstrating how routes, controllers, and views work together in a complete request cycle. The example creates a controller with a welcome action, sets an instance variable, updates the view to display it, adds a route, and runs the server to see the result.
- Generate a controller with the command
rails generate controller pages welcometo create both the controller and its view. - Define an instance variable (like
@name = "Ruby Learner") inside the controller action so the view can access and display it. - Edit the HTML file in
app/views/pages/welcome.html.erbto show the variable using embedded Ruby tags like<%= @name %>. - Add a route in
config/routes.rbwithget "/welcome", to: "pages#welcome"to map the URL to the controller action. - Start the server with
rails serverand visithttp://localhost:3000/welcometo see the page displaying "Welcome, Ruby Learner!" and the current year.
Chapter 7: Example Project – Build a Welcome Page
In this chapter we will build a complete welcome page, putting together routes, controllers, and views. This is the first practical example of the course and it shows the full request cycle in action.
✅ Step 1: Generate the Controller
Generate a controller with a welcome action:
rails generate controller pages welcome
✅ Step 2: Add an Instance Variable
Open app/controllers/pages_controller.rb and add an instance variable inside the action:
# app/controllers/pages_controller.rb
class PagesController < ApplicationController
def welcome
@name = "Ruby Learner"
end
end
✅ Step 3: Edit the View
Open app/views/pages/welcome.html.erb and display the variable:
<h1>Welcome, <%= @name %>!</h1>
<p>You have successfully built your first Rails page.</p>
<p>The current year is <%= Time.now.year %>.</p>
✅ Step 4: Add a Route
Add a route for the page in config/routes.rb:
# config/routes.rb
get "/welcome", to: "pages#welcome"
✅ Step 5: Run the Server
Start the server and visit http://localhost:3000/welcome:
rails server
You should see a page that says “Welcome, Ruby Learner!” along with the current year. That is the entire request cycle: route, controller, view – working together.
🏠 Practice Exercises
Extend the welcome page on your own:
<h1>Welcome, <%= @name %>!</h1>
<p>Today's date is <%= Date.today.strftime("%B %d, %Y") %>.</p>
<% if Time.now.hour < 12 %>
<p>Good morning!</p>
<% else %>
<p>Good afternoon or evening!</p>
<% end %>
Try adding a second variable, such as @city, and displaying it in the view. In the next chapter you will build a full blog application with a database.
