🚀Ruby on Rails for beginners: build an online store with Rails
Tags: webdev, ruby, rails, beginners
Published: 2023-11-22 13:05:48

Hello! Today we will be building a simple online store with Ruby on Rails.

## Table of Contents
&nbsp;1. [Prerequisites](#prerequisites)
&nbsp;2. [What is Ruby on Rails](#what-is-ruby-on-rails)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2.1. [Benefits of Ruby on Rails](#benefits-of-ruby-on-rails)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2.2. [Does anyone still use Ruby and Rails?](#does-anyone-still-use-ruby-and-rails)
&nbsp;3. [How to install Ruby on Rails](#how-to-install-ruby-on-rails)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3.3. [Installing Ruby:](#installing-ruby)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3.4. [Installing Rails](#installing-rails)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3.5. [Verify Installation:](#verify-installation)
&nbsp;4. [Starting your first Ruby on Rails project](#starting-your-first-ruby-on-rails-project)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 4.6. [Create a Project Directory:](#create-a-project-directory)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 4.7. [Generate a Rails Application:](#generate-a-rails-application)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 4.8. [Starting the Rails Server:**](#starting-the-rails-server)
&nbsp;5. [Understanding the MVC Architecture in Rails](#understanding-the-mvc-architecture-in-rails)
&nbsp;6. [Building a Simple Online Store Application in Rails](#building-a-simple-online-store-application-in-rails)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 6.9. [Generating Models and Migrations](#generating-models-and-migrations)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; a. [Migrations](#migrations)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 6.10. [Using a model to interact with the database](#using-a-model-to-interact-with-the-database)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 6.11. [Creating Controllers](#creating-controllers)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 6.12. [Designing Views](#designing-views)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 6.13. [Establishing Routes](#establishing-routes)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 6.14. [Running the Application](#running-the-application)

&nbsp; 7. [Conclusion](#conclusion)

## Prerequisites
- **Ruby Programming Language:** Familiarity with the Ruby programming language is essential, as Ruby on Rails is built upon it. You can learn Ruby through various online tutorials, books, and courses.

- **Development Environment:** Set up a suitable development environment on your computer. This typically involves installing Ruby, Rails, and a text editor or IDE like **Visual Studio Code** or **RubyMine**.


##What is Ruby on Rails

Ruby on Rails, a popular web application framework, simplifies the process of building robust and scalable web applications by providing a structured framework and eliminating the need to start from scratch. It leverages **the Model-View-Controller (MVC)** architecture, separating concerns into three distinct layers: **Model, View, and Controller**.

The Model layer handles data storage, retrieval, and manipulation, ensuring data accuracy and consistency. The View layer generates HTML content for web pages, while the Controller acts as the intermediary, handling user interactions, retrieving data from the Model, and preparing it for presentation in the View.

Ruby on Rails is built upon the Ruby programming language, known for its versatility and ease of use. With Ruby, you'll manipulate data, handle user inputs, and create dynamic web pages.

### Benefits of Ruby on Rails

![Benefits of Ruby on Rails](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vyd5fzaqe36jqs4yyk4g.jpg)

### Does anyone still use Ruby and Rails?
The answer to that question is yes! Some big organisations use Ruby and/or Ruby on Rails including our very own Dev.to. Dev Community is powered by Rails ❤


![Companies that use Ruby on Rails](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6d0ro3guh01gh4y862ub.jpg)


![Top Ruby on Rails websites](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/76kc7sgqqavvma14fr2x.png)

##How to install Ruby on Rails 
###Installing Ruby:

Ruby is the foundation upon which Ruby on Rails is built. Download and install the latest Ruby version from the [official RubyInstaller website](https://rubyinstaller.org/). This will provide you with the Ruby programming language and its associated tools.

###Installing Rails

Once Ruby is installed, proceed to install the Rails framework. You can use the RubyGems package manager to install Rails. On your terminal, type:

```bash
gem install rails
```

This command will download and install the Rails framework, providing you with the necessary tools for building web applications using Ruby on Rails.

###Verify Installation:

To ensure Ruby and Rails are installed correctly, check their versions using the following commands on your terminal:

```bash
ruby -v
rails -v
```

These commands should display the installed versions of Ruby and Rails, respectively.

##Starting your first Ruby on Rails project
 
###Create a Project Directory:

You need to create a directory to house your Rails project. Navigate to the desired location on your terminal and create a new directory using the `mkdir` command:

```bash
mkdir my-rails-app
```
You can alternatively do this using the GUI to create the directory.

### Generate a Rails Application:

Within the project directory, on your terminal, generate a new Rails application using the `rails new` command:

```bash
rails new my-rails-app
```

This command will generate the basic structure for your Rails application, including the necessary files, folders, and configuration settings.

###Starting the Rails Server:

To run your Rails application, start the Rails server using the following command:

```bash
bin/rails server
```

_If you are using Windows, you have to pass the scripts under the bin folder directly to the Ruby interpreter e.g. `ruby bin\rails server.`_


This command will start the Rails server and open your application in your web browser.
To see your application in action, open a browser window and navigate to http://localhost:3000. 
You should see the Rails welcome page indicating that your application is running successfully.


##Understanding the MVC Architecture in Rails

The MVC architecture serves as the foundation of Ruby on Rails applications. It separates the application's concerns into three distinct layers:

- **Model:** The model layer represents the data of the application. It is responsible for managing data interactions with the database, including creating, reading, updating, and deleting (CRUD) operations.

- **View:** The view layer handles the presentation of data to the user. It generates HTML content, the building blocks of web pages, that are displayed in the web browser.

- **Controller:** The controller acts as the intermediary between the model and the view. It handles user interactions, retrieves data from the model, and prepares it for presentation in the view.

## Building a Simple Online Store Application in Rails

To demonstrate the application of the MVC architecture, let's build a simple online store application using Ruby on Rails:

###Generating Models and Migrations

Begin by defining the models for the application's data. 
_Model names are singular, because an instantiated model represents a single data record. To help remember this convention, think of how you would call the model's constructor: we want to write Product.new(...), not Products.new(...)._

In this case, we'll create a `Product` model to represent products in the online store:

```bash
rails generate model Product name:string description:text price:decimal
```

This command generates a `Product` class in the `app/models` directory. The attributes specified in the command define the product's characteristics: name, description, and price.

####Migrations 
Migrations are used to alter the structure of an application's database. In Rails applications, migrations are written in Ruby so that they can be database-agnostic.
Migrations are responsible for creating and modifying the database schema to accommodate the data models. Generate a migration for the `Product` model:

```bash
rails db:migrate
```

This command creates a migration file that defines the table structure for storing product information in the database.

###Using a model to interact with the database
To play with our model a bit, we're going to use a feature of Rails called the console. The console is an interactive coding environment just like irb, but it also automatically loads Rails and our application code.

Let's launch the console with this command on our console:

```bash
bin/rails console
```

You should see an irb prompt like:

```bash
Loading development environment (Rails 7.1.0)
irb(main):001:0>
```

At this prompt, we can initialize a new Product object:

```bash
irb> product = Product.new(name: "Hot towel", description: "Specially heated towel for your skin", price: 99.99)
```

_It's important to note that we have only initialized this object. This object is not saved to the database at all. It's only available in the console at the moment. To save the object to the database, we must call `save`:_

```bash
irb> product.save
(0.1ms)  begin transaction
Article Create (0.4ms)  INSERT INTO "products" ("name", "description", "price", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["name", "Hot towel"], ["description", "Specially heated towel for your skin"], ["price", "99.99"], ["created_at", "2023-11-18 23:47:30.734416"], ["updated_at", "2023-11-18 23:47:30.734416"]]
(0.9ms)  commit transaction
=> true
```
The above output shows an INSERT INTO "products" ... database query. This indicates that the product has been inserted into our table. 

###Creating Controllers

Controllers handle user interactions and manage the flow of data between the model and the view. Generate a controller for managing products:

```bash
rails generate controller Products
```

This command creates a `Products` controller in the `app/controllers` directory. The controller will contain actions for listing, showing, creating, updating, and deleting products.

###Designing Views

Views are responsible for generating the HTML content that the user sees in the web browser. Create a view for listing products:

```html
<h1>Products</h1>

<% @products.each do |product| %>
  <div class="product">
    <h2><%= product.name %></h2>
    <p><%= product.description %></p>
    <p>Price: <%= product.price %></p>
    <a href="/products/<%= product.id %>">Show</a>
    <a href="/products/<%= product.id %>/edit">Edit</a>
    <a href="/products/<%= product.id %>/delete">Delete</a>
  </div>
<% end %>
```

This view iterates through the `@products` collection, displaying each product's name, description, price, and links to actions for viewing, editing, and deleting the product.

Similarly, you can, at your own time, create views for showing product details, creating new products, editing existing products, and deleting products. Each view should display the relevant information and provide appropriate forms for user interactions.

###Establishing Routes

Routes define the mapping between URLs and controller actions. Configure routes in the `config/routes.rb` file:

```ruby
Rails.application.routes.draw do
  resources :products
end
```

This configuration defines routes for all the standard CRUD actions (index, show, new, edit, create, update, and destroy) for the `Products` controller.

###Running the Application

Start the Rails server to run the application.

```bash
rails s
```

This command starts the Rails server and opens the application in your web browser. You can now navigate through the application, view products, add new products, and manage product information.

##Conclusion

This has been a brief and not-so-detailed overview of creating your first Ruby on Rails application: a simple online store. 
There is still so much to be learnt and so much that  can be built on this simple app. I encourage you to check out the [Rails documentation](https://guides.rubyonrails.org/getting_started.html#mvc-and-you-generating-a-model) for a more detailed guide on creating your first Ruby on Rails web application.

If you have any questions, please feel free to ask in the comment section. 
Connect with me on [Linkedin](www.linkedin.com/in/dumebi-okolo).
Let's connect on [X(formerly twitter)](https://twitter.com/DumebiTheWriter).

[Image: Benefits of Rails](https://www.google.com/url?sa=i&url=https%3A%2F%2Fmedium.com%2Fquick-code%2Ftop-8-reasons-why-ruby-on-rails-is-the-best-web-development-technology-3016824e6d34&psig=AOvVaw1o73wAymwWhQzT2qiFFrbX&ust=1700743766747000&source=images&cd=vfe&opi=89978449&ved=0CBQQjhxqFwoTCNjO47fS14IDFQAAAAAdAAAAABAh)
[Image: who still uses Ruby](https://www.google.com/url?sa=i&url=https%3A%2F%2Frubyroidlabs.com%2Fblog%2F2019%2F10%2F9-industries-where-flagship-companies-choose-ruby-on-rails%2F&psig=AOvVaw1o73wAymwWhQzT2qiFFrbX&ust=1700743766747000&source=images&cd=vfe&opi=89978449&ved=2ahUKEwizjuux0teCAxXPuicCHf8WCxAQr4kDegQIARBk)
[Cover image](https://www.google.com/url?sa=i&url=https%3A%2F%2Faldibs.com%2Fen%2Fdeferencias-en%2F&psig=AOvVaw1o73wAymwWhQzT2qiFFrbX&ust=1700743766747000&source=images&cd=vfe&opi=89978449&ved=2ahUKEwizjuux0teCAxXPuicCHf8WCxAQr4kDegUIARCPAQ)
[Rails official documentation](https://guides.rubyonrails.org/getting_started.html#mvc-and-you-generating-a-model)