Ruby on Rails / Introduction to Ruby on Rails

Creating Your First Rails Application

This tutorial takes you through creating your first Rails application. We will cover the steps from initializing the application to running it on your local server.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers the fundamentals of Ruby on Rails, its history, and the MVC architecture.

1. Introduction

In this tutorial, we will be building your first Rails application, a simple blog. We will start from scratch, explaining each step in detail with clear code examples. By the end of this tutorial, you will have a functioning Rails application running on your local server.

You will learn:
- How to install Rails on your machine
- How to create a new Rails application
- How to generate a model, view, and controller
- How to route traffic to your application
- How to interact with a database using ActiveRecord
- How to create a simple user interface with HTML and CSS

Before you start, you should have a basic understanding of Ruby language, HTML and CSS. You should also have Ruby and Rails installed on your computer. If you have not installed Rails yet, you can follow this guide.

2. Step-by-Step Guide

Installing Rails and Creating a New Application

Open your terminal and type the following command to install Rails:

gem install rails

Then, create a new Rails application using the rails new command followed by the name of your application. In our case, we'll name our application "blog":

rails new blog

Navigate into your new application's directory:

cd blog

Generating a Model, View, and Controller

In Rails, the application's data and business logic are handled by Models, the user interface is handled by Views, and the web requests are handled by Controllers. This pattern is known as MVC (Model, View, Controller).

To create a new model, view, and controller for our blog posts, use the following command in your terminal:

rails generate scaffold Post title:string body:text

This command will generate a Post model with a title and body, a Posts Controller, and views for the different actions (index, show, new, edit).

Setting the Routes

Open the file config/routes.rb in your text editor. This file is where you define how URLs map to the controller's actions.

Set the root route to the index action in PostsController:

Rails.application.routes.draw do
  root 'posts#index'
  resources :posts
end

Interacting with the Database

Before you can use your application, you need to run a migration to update your database schema:

rails db:migrate

Starting Your Application

Start your Rails server with the following command:

rails server

You can now access your application by visiting http://localhost:3000 in your web browser.

3. Code Examples

Here are some code examples from our blog application:

This is the create action in the PostsController (app/controllers/posts_controller.rb):

def create
  @post = Post.new(post_params)

  if @post.save
    redirect_to @post
  else
    render 'new'
  end
end

This action attempts to save a new post to the database. If the save is successful, it redirects to the show view for that post. If the save is not successful, it renders the new view again.

This is the form for creating a new post (app/views/posts/new.html.erb):

<%= form_for @post do |f| %>
  <p>
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </p>

  <p>
    <%= f.label :body %><br>
    <%= f.text_area :body %>
  </p>

  <p>
    <%= f.submit %>
  </p>
<% end %>

This form uses form helpers to create the form fields. It creates fields for the title and body of the post, and a submit button.

4. Summary

Congratulations, you've built your first Rails application! You've learned how to install Rails, create a new Rails application, generate a model, view, and controller, set the routes, interact with the database using ActiveRecord, and start your Rails server.

For further learning, you could explore adding user authentication, creating more complex models and relationships, or deploying your application to a hosting platform like Heroku.

Some resources to help you continue your learning journey are:
- Rails Guides
- The Ruby on Rails Tutorial
- RailsCast

5. Practice Exercises

Exercise 1: Add Comments to Your Blog

Create a new scaffold for comments that belong to posts. Each comment should have a name (string) and body (text).

Exercise 2: Add User Authentication

Use the Devise gem to add user authentication to your blog. Users should be able to sign up, log in, and log out. Only logged-in users should be able to create posts.

Exercise 3: Deploy Your Application to Heroku

Follow the Heroku guide for Rails 5 to deploy your blog to Heroku. Make sure to add a Procfile to your application and to run your migrations on Heroku.

For each exercise, remember to run rails db:migrate after generating new migrations. Always check your application in the browser to make sure everything is working as expected.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Robots.txt Generator

Create robots.txt for better SEO management.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help