Ruby on Rails app to demonstrate database concepts

Do not miss this exclusive book on Binary Tree Problems. Get it now for free.

Project

On this post, we’ll talk about the most popular databases in RoR web development, walk you through the process of integrating them, and describe the best practices.
In this tutorial we will build a static page with a button CreateTimeline which when clicked makes a record with the current time. On another page, the recent clicks as rows and total number of clicks will be displayed. We will add a delete button with each click row.

Databases

A database is a file that stores organized information.” Organization” is a keyword – databases group objects according to their values, characteristics, hierarchy. Databases use formal structure and models to show relationships between data. When your application scales, you can still easily trace every file.

Which database to choose for ruby on rails app

Let’s take a look at the most common options:

  • PostgreSQL: it’s one of the most cost-efficient, performing, and versatile SQL databases out there.
  • SQLite Rails comes with built-in support for SQLite, which is a lightweight serverless database application.
  • MySQL: arguably the most popular SQL database right now. Its requirements are less rigid than those of PostgreSQL – the software doesn’t return errors as often.

How to make a postgresql database in Rails

On this tutorial we will chose PostgreSQL because it’s stable, versatile, and popular. Users can easily add elaborate functionality and make changes to the data structure.

I'm assuming you already have postgresql installed on your machine, created a user with a password.It's very important that you have a user created on your postgresql because this profile will be syncronized with ruby on rails page and used to issue back and forth commands.

Setting up postgres database with rails

Next, you need to build a bridge between your database management system and RoR application, in this tutorials we will look at two ways to make the setup;

  1. Create a new rails project together with postgresql database.

Run the following command;

rails new [application name] -d postgresql

This will install rails application dependencies together with required postgresql dependencies.

  1. Setup Postgresql to an existing rails project.
    You will need to cd to your existing rails project on your machine.
    Open config/database.yml file and you will see that by default rails application support sqlite3 database, so to add postgresql in rails application we will have to remove sqlite3 and replace with postgres. To do so, open Gemfile then inside the file replace gem ‘sqlite3’, ‘~> 1.4’ with the commands below;
gem 'pg'

After adding pg gem in gemfile run the below command on terminal;

bundle install

This command installs all necessary files for implementing the PostgreSQL database.

Configure postgresql

Once we have setup postresql, next we will need to configure our database in the rails app so as to create a connection. Open the config/database.yml file, under default: &default add the following code;

default: &default
adapter: postgresql
encoding: unicode
# For details on connection pooling, see Rails configuration guide
# https://guides.rubyonrails.org/configuring.html#database-pooling
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
username: your_postgresql_username
password: your_postgresql_password

After adding the data in config/database.yml file you have to run the given command;

rails db:create

Test the database connection

we test our database connection to our rails app by starting the rails server. Using the following command:

rails server

Once it's done you should see the following message:

[user@localhost my-app]$ bin/rails server
=> Booting Puma
=> Rails 5.0.0.1 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.6.0 (ruby 2.3.1-p112), codename: Sleepy Sunday Serenity
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://localhost:3000

Open your htps://localhost:3000 to be sure that the server is running. You sould see rails smoke test page as shown below;

Active record

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic.
Read more on rails active record

Create a rails Model

A Rails Model is a Ruby class that can add database records find particular data you're looking for, update that data, or remove data. These common operations are referred to by the acronym CRUD--Create, Remove, Update, Destroy.

In this tutorial we will create a model with the name ClickTimeline run the command below;

rails generate model clickTimeline

As we'll see in the command line, the model generator generates a number of files for us:

invoke  active_record
create    db/migrate/20230131094005_create_click_timelines.rb
create    app/models/click_timeline.rb
invoke    test_unit
create      test/models/click_timeline_test.rb
create      test/fixtures/click_timelines.yml

The first file created is migration file then the model file as the second.

Migration File

The model generator generates for us a migration file in the db/migrate like all other migrations files. Migrations describe the changes we'll be making to our database (though haven't actually enacted just yet). In this case, the generated migrations file says:

class CreateClickTimelines < ActiveRecord::Migration[7.0]
  def change
    create_table :click_timelines do |t|

      t.timestamps
    end
  end
end

The call to create_table specifies how the click_timelines table should be constructed. By default, the create_table method adds an id column as an auto-incrementing primary key. So the first record in the table will have an id of 1, the next record will have an id of 2, and so on.
Inside the block is a call to t.timestamps. This method defines two additional columns named created_at and updated_at. As we will see, Rails will manage these for us, setting the values when we create or update a model object.
With this files already created for us we can run our migration by running the following command on the terminal;

rails db:migrate

The command will display output indicating that the table was created:

4 files changed, 28 insertions(+)
 create mode 100644 blogApp/app/models/click_timeline.rb
 create mode 100644 blogApp/db/migrate/20230131094005_create_click_timelines.rb
 create mode 100644 blogApp/test/fixtures/click_timelines.yml
 create mode 100644 blogApp/test/models/click_timeline_test.rb

If you check db/schema.rb our table should be created. As shown below;

 create_table "click_timelines", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

The table has created_at and updated_at columns which is the timestamp that rails generates.

Model File

Now we can interact with the table using our model file app/models/click_timeline.rb, open it;

class ClickTimeline < ApplicationRecord
end

The file creates a User class, which is a Model class. This class is the object we'll use to perform CRUD operations on the database, it's the thing we really wanted to create to make our lives easier and it inherits from ApplicationRecord. Check more about models in ruby on rails documentation

Submit form data to the database

We need to makes a record in the database with the current time when the button on our home page is clicked. For that we will need a controller;

Action Controllers
A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class. We will create a controller with the the methods create which will have the button and view method which will display the recent clicks as rows and total number of clicks.
Run the following commands:

rails g controller Timeline new index

It will create a file in the controller and view folders.
Let's open app/controllers/timeline_controllers.rb

Inside the file you will see the two methods, new and index. Edit your methods to look like the one shown below;

 def index
    @clicktimelines = ClickTimeline.all
    @counttimelines = ClickTimeline.all.count
  end

  def new
    @clicktimeline = ClickTimeline.new

  end

  def create
    @clicktimeline = ClickTimeline.new
    @clicktimeline.save
    redirect_to root_path
  end
   
  def destroy
    @clicktimeline = ClickTimeline.find(params[:id])
    @clicktimeline.destroy
    redirect_to root_path
  end

The index method is used to fetch all records from the database. The new method will be used to create a new timeline (which will contain created_at and updated_at) whenever a user clicks on the ClickTimeline button on the form. create method is used to push the form's contents to the database. destroy method is used to delete records from the database

Move to your config/routes.rb file, make the following chnages;

root "timelines#index"
get 'timelines', to: 'timelines#index'
post 'timelines', to: 'timelines#create'
get '/timelines/new', to: 'timelines#new', as: 'new_timeline'
get '/timelines/:id', to: 'timelines#destroy'
delete '/timelines/:id', to: 'timelines#destroy', as: 'timeline'

You can find out more about routing on rails documentation.
Next we will create a form with our button, open the file app/views/timeline/new.html.erb ;

<h1>Click Timeline</h1>
<%= form_with model: @clicktimeline, url: timelines_url, method: :post do |form|  %>
    <div class="actions">
        <%= form.submit 'CreateTimeline' %>
    </div>
<% end %>

We have created a form using form_tag rails helper, and action timeline with submit_tag ClickTimeline as the button. Run rails server, you should see the following when you open the route http://localhost:3000/timeline/new ;

Once you click the button you should be redirected to the root page as shown below;

You should see the following on your terminal;

You should see Insert into sql commands to show that it has inserted created_at and updated_at to our table click_timelines. That's how send form data to the database.

Fetch records from the database

In our index page (root page) we want to display the recent clicks and the total number of clicks with a delete button in a table. Remember our index method? That method is used to fetch all records from the database, we will now go to our app/views/timeline/index.html.erb to create a table and populate it with our records from the database as shown below;

<h1>Click Timeline</h1>
<div class="table-container">
<table class="table">
        <tr>
        <th >Created at</th>
        <th>Updated at</th>
        <th>Action</th>
        </tr>
    <tbody>
        <% @clicktimeline.each do |timeline| %>
        <tr>
            <td><%= timeline.created_at %></td>
            <td><%= timeline.updated_at %></td>
            <td><button>Delete</button></td>
        </tr>
        <% end %>
    </tbody>
</table>
</div>

We will loop the @clicktimeline variable as it contains all our records as shown on the code. Let's now style our table as shown in app/assets/stylesheets/style.css

table, td, th {
  border: 1px solid;
}

td, th {
  padding: 9px;
}

Go to your rootpath http://localhost:3000/ and you should see the following;

Your total number of records may vary depending on how many times you clicked the button.

Delete records from the database

Remember the destroy method? That is used to take care of deletion of records from the database. When you click the delete link, it should delete the specific record from the database and it will also be removed from your table.

With this article at OpenGenus, you must have the complete idea of database concepts in RoR applications.

Sign up for FREE 3 months of Amazon Music. YOU MUST NOT MISS.