Just for those following along, I’m learning how to create a new app: How to create a new Rails application: rails new test_app (where “test_app” is the name of the program) and add an
I first have to make a new route in the config folder in my new app. I do that by loading my app in Atom (or a similar editor) and drilling down in the file tree to the config folder. Open routes.rb and create a new path by typing
get 'pages/home', to: 'pages#home'. This creates the route, but now I’ll need a controller and a view. To create a controller, find the controllers folder which is nested inside the app folder. Inside that folder, I’ll need to make a new file called pages_controller.rb. Once that file is created, I’ll need to put the following code in to inherit the stuff from the ApplicationController:
class PagesController < ApplicationControllerend
Then inside the pages_controller.rb file and inside the class PagesController, I’ll need to define the action(method): home.
class PagesController < ApplicationController def home endend
The last thing I need to create is the template for the page. Navigate to the views folder and create a new folder titled pages. Inside that folder create a new file titled home.html.erb. That page is the actual webpage, so put “This is the home page”(or whatever you want).
One additional note: to add a ruby code to a .erb file, you have to put the code between
%> brackets. If you want the code to actually show something on the screen of a web browser, the open bracket should be
<%= and closing should be
%>. A link would be:
<%= link_to 'Home Page', pages_home_path %> where 'Home Page' (is the text that will be the link) and pages_home_path is the path to the controller (pages) and the action or method (home) - which will get you to the actual Home Page. Don't forget the comma between the two (I wasted 15 minutes forgetting that earlier)...
Also... instead of having to type 0.0.0.0:3000 to see the rails server, and then having to type 0.0.0.0:3000/pages/home to get to the home page, you can make 0.0.0.0:3000 be the home page. You just have to go to the routes.rb (in the config folder and change the code from this:
get 'pages/home', to: 'pages#home' to this:
root 'pages#home'.Once that is changed, make sure to update the path to
<%= link_to 'Home Page', root_path %>