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
Step 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.
To create the database table for the Course model, run the following command in terminal.
rails db:migrate
Step 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)
2. 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
Step 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
Step 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.
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.
<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.
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:
How to Retrieve Data from Database in Rails?
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.