Rails can create dynamic pages. A page is dynamic if the contents is not the same each url request. Think of a page like a clock, countdown, weather or even products.

To make a dynamic page, you need to use the model-view-controller principle. Make a few files (model, view, controller, router) to create a dynamic page. In this article I’ll show you how.

Rails App

Model

Rails gets data from models. A model can get its data from a database.

You can use rails generate model to create a new model. But you can also do it manually.

Enter directory app/model and add the file climate.rb.
Add this contents:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Climate

def predict
prediction = 'Sunny'
end

def temperature
temp = 30
end

def today
today = Date.today
end

end

View

The view is the template that is shown in the web browser. Enter the directory app/views/. Create directory weather mkdir weather.

Then add the file new.html.erb inside it with this contents:

1
2
3
<h3>Weather</h3>
<p>Weather prediction for <%= @climate.today %></p>
<p>Temperature <%= @climate.temperature %> and <%= @climate.predict %>

Create controller

The first step is to create a controller. In this example it will be named weather controller.
Create a controller called weather_controller.rb. Either add it in app/controllers/

Alternative is to use the command: rails generate controller weather index

In the controller link the model and view:

1
2
3
4
5
6
class WeatherController < ApplicationController
def new
@climate = Climate.new
render 'weather/new'
end
end

Routing

Then make a route to the controller. Open config/routes.rb.
Add the contents below:

1
2
3
Rails.application.routes.draw do
get 'weather' => 'weather#new'
end

dynamic pages in rails

Demo

Run the command rails server. It should show you the port its running on, e.g. 3000.

# rails server
=> Booting Puma
=> Rails 5.2.1 application starting in development
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.12.0 (ruby 2.5.1-p57), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000

Open the url http://localhost:3000/weather.
You should now see the dynamic content (weather prediction) show up.