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.

  1. Start command prompt (terminal) and navigate to your project directory
  2. Now execute the following command:
    rails generate controller static about_us contact_us
  3. This command will perform following actions:
    1. Creates a file in app\controllers
      static_controller.rb
    2. Added following code in this controller-
      class StaticController < ApplicationController
       def about_us
       end
       def contact_us
       end
      end
    3. Created following files in app\views\static folder-
      about_us.html.erb
      contact_us.html.erb
    4. Created a helper:
      app\helpers\static_helper.rb
    5. Added following routes in app\config\routes.rb
      get 'static/about_us'
      get 'static/contact_us'
  4. You can go ahead and start the server by the command:
    rails server
  5. 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