In this post, we will see how we can easily generate controller, methods as well as their views.
A controller is a class that have methods representing URLs in your web application. This means, if we want to have a URL like:
http://mysite.com/about-us
in our web application, we need to create a controller that contains a method representing the above URL.
Let us check an example for creating controllers and actions.
First you need to create a new Rails project by following this link
Let us say we want to create a controller for our website static pages like about, contactus etc.
- Start command prompt (terminal) and navigate to your project directory
- Now execute the following command:
rails generate controller static about_us contact_us
- This command will perform following actions:
- Creates a file in app\controllers
static_controller.rb
- Added following code in this controller-
class StaticController < ApplicationController def about_us end def contact_us end end
- Created following files in app\views\static folder-
about_us.html.erb contact_us.html.erb
- Created a helper:
app\helpers\static_helper.rb
- Added following routes in app\config\routes.rb
get 'static/about_us' get 'static/contact_us'
- Creates a file in app\controllers
- You can go ahead and start the server by the command:
rails server
- Now navigate to the url:
http://localhost:3000/static/contact_us http://localhost:3000/static/about_us
Now the above Urls looks ugly to me. To make it more readable, let’s make some changes in app\config\routes.rb file. Here we change the two lines for about_us and contact_us to the following two lines:
get '/contact-us' => 'static#contact_us' get '/about-us' => 'static#about_us'
Now navigate the Urls:
http://localhost:3000/static/contact_us http://localhost:3000/static/about_us