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 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.
app/model and add the file
Add this contents:
The view is the template that is shown in the web browser. Enter the directory
app/views/. Create directory weather
Then add the file
new.html.erb inside it with this contents:
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
Alternative is to use the command:
rails generate controller weather index
In the controller link the model and view:
class WeatherController < ApplicationController
Then make a route to the controller. Open
Add the contents below:
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
You should now see the dynamic content (weather prediction) show up.