Setting Up A New Rails Applications And Working With Controllers And Views

Controllers and views are the integral part of ruby on rails frameworks. The requests from the client is first sent to the server and the server directs the request to appropriate controller, the controllers in turn directs the request to a model  if necessary and connects it to the view to show the output tot the user. The image below shows how the frameworks handles requests from the clients.

Creating A Rails Application:

1) Set up the rails environment. Follow the link if you don’t have rails setup in your workstation. Setup Rails Environment

2)Once the rails environment is setup , open the terminal and create a directory where you can put your ruby project files. CD in to the directory and execute the following command to create a new rails applications. Here am gonna create a application called rails_demo. Once the command is executed, it will create all the necessary files needed for a rails application.
$ rails new rails_demo


3) Rails comes with a default webrick we server. Once your application is created , you can check if it is working by starting the rails server. You can access your application in the web browser using https://localhost:3000. Before starting the rails server make sure that your current directory is your application directory. In our example its rails_demo. Execute the following command to start the rails server.

$ rails server

After the server has started and if you access your application through web browser ,you will see a welcome message. Use Cntrl + C to stop the server.

Creating A Controller And And View:

In this example we will create a controller and view to access it from the web browser.
1)Create a controllers and view by executing the following command.
$ rails generate controller welcome index

In the above command welcome is the controllers name and index is the view which is associated with the controller. View is a  html document which renders the output to the users in the web browser. If you open the welcome controller present inside /demo_rails/app/controllers/welcome_controller.rb file, you can see that index in defined inside the welcome controller.
View is located in /demo_rails/app/views/welcome/index.html.erb
2) Now if you go the url http://localhost:3000/welcome/index you can see welcome message from the index view. It is just a html message which get created by default. You can try adding other html tags , scripts etc.. and view it in the browser.
In the url welcome is the controller name and index is the view name. It is how rails routes the requests. When a controller is called ,the controller connects the view associated with it and shows the output in the web browser. 
Leave a comment for more queries.

Other Interesting Blogs

Leave a Comment

Share via
Copy link
Powered by Social Snap