How to Retrieve Data from Database in Rails?
Last Updated :
08 May, 2024
In this article, we'll be creating a new Rails project, setting up a database, adding demo data, and retrieving that data to display in your application.
Steps to Retrieve Data from Database
Step 1: Create a Project
You can create a new Rails project using the following command in your terminal.
rails new railsapp
Create a ProjectStep 2: Generate Model and Migration
Let's say we want to create a 'Course' model which will have it's name and price. Run the following command in your terminal.
rails generate model Course name:string price:decimal
This command will generate a model file (course.rb) in the app/models directory and a migration file in the db/migrate directory.
Create ModelTo create the database table for the Course model, run the following command in terminal.
rails db:migrate
Run migrationStep 3: Create Demo Data
You can create some demo data for the Course model by either using Rails console or by creating a seed file.
1. Using Rails console: Run this command in terminal to open the Rails console.
rails console
Now, run this command in your rails console it will create a row in your Course table.
Course.create(name: "Web Development", price: 499.99)
Create rows using rails console2. Using seed file: Go to 'db/seeds.rb' and add these lines to create data in your Course model.
Course.create(name: 'AIML', price: 399)
Course.create(name: 'Data Science', price: 650.99)
# Add more courses if you want
Then run the following command in your terminal to execute the seed file.
rails db:seed
Create DatabaseStep 4: Generate a Controller
Run the following command in your terminal. This will generate a 'course_controller.rb' file in the 'app/controllers' directory with an 'index' action.
rails generate controller Course index
Generate a ControllerStep 5: Retrieve Data
Now, you can retrieve the data from the Course model in your Rails application. For example, you can retrieve all coourses and display their names and prices. Open 'course_controller.rb' in the 'app/controllers' directory and add the following code.
Ruby
class CourseController < ApplicationController
def index
@course = Course.all
end
end
Step 6: Display Data
Now, open your view file that is 'index.html.erb' in 'app/views/course' and write the below code. It will display the retrieved data on a web page.
HTML
<h1>Courses</h1>
<ul>
<% @course.each do |course| %>
<li><%= course.name %> - <%= number_to_currency(course.price) %></li>
<% end %>
</ul>
Step 7: Set Up Routes
Finally, set up the route to access the index action of the 'CourseController'. Open the 'config/routes.rb' file and add the following line. It will display the index page instead of Rails default page.
Ruby
Rails.application.routes.draw do
resources :course
root 'course#index'
end
Step 8: Run the Server
Now, run the below command to start the server and open 'http://localhost:3000' in your browser.
rails server
Output:
Output
Similar Reads
How to retrieve data from MySQL database using PHP ?
There are steps to understand for retrieving the data from the MySQL database. Approach: Create the database, then create the table for data.Enter the rows in the table. You have to connect to the database. Now we understand each and every step as shown below.  Example 1: In this. we use PHPMyAdmin
2 min read
How to fetch data from the database in PHP ?
Database operations in PHP are a very crucial thing that is especially needed in CRUD (Create, Read, Update and Delete) operations. In this article, we will discuss the Read part i.e. data fetching from database. There are two ways to connect to a database using PHP. They are as follows. MySQLi ("i"
4 min read
How to Retrieve Data from MongoDB Using NodeJS?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for the storage and retrieval of data. Thi
3 min read
How to Add Data from Queryset into Templates in Django
In this article, we will read about how to add data from Queryset into Templates in Django Python. Data presentation logic is separated in Django MVT(Model View Templates) architecture. Django makes it easy to build web applications with dynamic content. One of the powerful features of Django is fet
3 min read
How to Design a Database for Railway Reservation System Like IRCTC
A railway reservation system like IRCTC (Indian Railway Catering and Tourism Corporation) manages millions of users and transactions daily, handling bookings, cancellations, passenger information, and real-time updates. Efficient database design ensures smooth operations, quick response times and a
6 min read
How to create API in Ruby on Rails?
Building APIs with Ruby on Rails: A Step-by-Step GuideRuby on Rails (Rails) is a popular framework for web development, known for its convention over configuration approach. It also excels in creating robust and maintainable APIs (Application Programming Interfaces). APIs act as intermediaries, allo
3 min read
How to Show Database in PL/SQL
PL/SQL is the Procedural Language/Structured Query Language and serves as a procedural language built-in extension to SQL language, which allows seamless integration of procedural constructs with SQL. One of the most common functions of a DBMS is the retrieval of information about databases which is
4 min read
Ruby on Rails - Database Setup
Ruby and Rails is a powerful web software framework that simplifies database control and interactions. right database setup is crucial for any Rails utility, as it guarantees efficient information garage and retrieval. This guide will walk you through putting in databases on your Rails application,
5 min read
Sending data from a Flask app to PostgreSQL Database
A database is used to store and maintain persistent data that can be retrieved and manipulated efficiently. we usually need a database, an organized collection of data for example in an e-commerce web app where we need to store the data about the users, orders, carts, shipping, etc. In a database, d
6 min read
How to create table in Ruby on Rails?
In Ruby on Rails, creating tables involves using migrations, which are a powerful mechanism for managing database schema changes. Here's a detailed breakdown of the process: 1. Database Setup (Optional): While APIs can function without databases, many Rails applications use them for data persistence
3 min read