Hello! Today we will be building a simple online store with Ruby on Rails.
Table of Contents
1. Prerequisites
2. What is Ruby on Rails
2.1. Benefits of Ruby on Rails
2.2. Does anyone still use Ruby and Rails?
3. How to install Ruby on Rails
3.3. Installing Ruby:
3.4. Installing Rails
3.5. Verify Installation:
4. Starting your first Ruby on Rails project
4.6. Create a Project Directory:
4.7. Generate a Rails Application:
4.8. Starting the Rails Server:**
5. Understanding the MVC Architecture in Rails
6. Building a Simple Online Store Application in Rails
6.9. Generating Models and Migrations
a. Migrations
6.10. Using a model to interact with the database
6.11. Creating Controllers
6.12. Designing Views
6.13. Establishing Routes
6.14. Running the Application
7. 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
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 ❤
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. 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:
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:
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:
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:
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:
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:
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:
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:
bin/rails console
You should see an irb prompt like:
Loading development environment (Rails 7.1.0)
irb(main):001:0>
At this prompt, we can initialize a new Product object:
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
:
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:
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:
<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:
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.
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 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.
Let's connect on X(formerly twitter).
Image: Benefits of Rails
Image: who still uses Ruby
Cover image
Rails official documentation
Top comments (7)
Hey Dumebi ,if you don't mind ,can ypu please be my mentor?🙏🙏
Where can i often get intouch with?
Hi. You can find me on my LinkedIn.
Just connected with you Dumebi
Awesome!
Very nice introduction article to Rails :), i'll send it to folks who want a quick and understandable introduction to it !
(be careful you have a typo in What is Ruby on Rails)
Hiii. Thank you so much!! I appreciate it. ❤️ ❤️
Some comments may only be visible to logged-in visitors. Sign in to view all comments.