CRUD Post for Blog application

Build Blog with Ruby on Rails (Part 2)
Luan Nguyen
Luan Nguyen
Aug 21, 2020 · 5 min read

robert-collins-tvc5imO5pXk-unsplash.jpg 570 KB

This is part 2 in Project: Build Blog with Ruby on Rails

What’ll you learn?

  • Installing PostgreSQL in Ruby on Rails application
  • Introduction to Active Record
  • Understanding CRUD in Active Record
  • Creating CRUD Post for Blog application

Installing PostgreSQL

On Mac OSX: You can install PostgreSQL server and client from Homebrew:
brew install postgresql

Start Postgresql service:
brew services start postgresql

Using PostgreSQL in Rails application by adding gem pg’ to the Gemfile
gem 'pg'

Run bundle to install pg gem.
bundle install

Configure database
default: &default
 adapter: postgresql
 pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
 timeout: 5000
 <<: *default
 database: development_blog
 <<: *default
 database: test_blog
 <<: *default
 database: production_blog

Create databases for your blog application
Using the migration command to create databases for the application.
rails db:create
>> Created database 'development_blog'
>> Created database 'test_blog'

Introducation to Active Record

What is Active Record?
  • Active Record is the M in MVC - the model - which is the layer of the application responsible for representing data and business logic.
  • It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.
  • ORM is a technique that connects the rich objects of an application to tables in a relational database management system (RDBMS). Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.
Active Record as an ORM Framework which supports important features as:
  • Represent models and their data.
  • Represent associations between these models.
  • Represent inheritance hierarchies through related models.
  • Validate models before they get persisted to the database.
  • Perform database operations in an object-oriented fashion.

Active Record Conventions
  • Class name is singular
  • DB table name is plural
  • Need to have an id primary key
Example:  Post -> posts, Person  -> people, BookStore -> book_stores

Create the Post model

Models in Rails use a singular name, and their corresponding database tables use a plural name. To create Post model, we use generator of Rails and type command in your terminal:
rails generate model Post title:string content:text

This command will generate a bunch of files:
Running via Spring preloader in process 5011
      invoke  active_record
      create    db/migrate/20200818091640_create_posts.rb
      create    app/models/post.rb
      invoke    test_unit
      create      test/models/post_test.rb
      create      test/fixtures/posts.yml

Now, we need to consider 2 files are app/models/post.rb and db/migrate/20200818091640_create_posts.rb

db/migrate/20200818091640_create_posts.rb in editor:
class CreatePosts < ActiveRecord::Migration[5.1]
  def change
    create_table :posts do |t|
      t.string :title
      t.text :content


This file is a migration that will create Posts table with columns: 
  • title : type string
  • content: type text
  • primary key id : type integer (default column)
  • created_at and updated_at: type datetime (default columns)
Run the migration to execute creating Posts table:
rails db:migrate

and see the result:
== 20200818091640 CreatePosts: migrating ======================================
-- create_table(:posts)
   -> 0.0404s
== 20200818091640 CreatePosts: migrated (0.0405s) =============================

More about migrations, refer to Active Record Migrations.

Open Post model:
class Post < ApplicationRecord

This is Post model which mapped to a posts table in the our database.

Understanding CRUD in Active Record Model

CRUD is an acronym for the 4 verbs we use to operate on data: Create, Read, Update, Delete. Active Record automatically creates methods to allow an application to read and manipulate data stored within its tables.

We'll use Rails console to learn about CRUD methods of Active Record.
The Rails console is where you interact with your Rails application from the command line. 
To use it we type to the command line:
rails console  # or rails c
You'll look like: 
Running via Spring preloader in process 23513
Loading development environment (Rails 6.0.x.x)
2.6.3 :001 >

Create a Post
Using the create method to create and save a new record into the database:
# Run in the rails console
post = Post.create(title: "Title of Post", content: "Content of Post")

Using the new method, an object can be instantiated without being saved:
# Run in the rails console
post =
post.title = "Title of Post"
post.content = "Content of Post"

A call to will commit the record to the database.

Active Record provides a rich API for accessing data within a database. Examples:
# Get all posts

# Get a Post
Post.first # Get first Post
Post.last # Get last Post

# Get the first post with the title is 'Title of Post'
post = Post.find_by(title: 'Title of Post')
post = Post.where(title: 'Title of Post').first

# Order all posts by created_at:
posts = Post.all.order(created_at: :desc)
posts = Post.all.order(created_at: :asc)

We'll learn more about query in Active Record model in an other article.

Update a Post
post = Post.find_by(title: 'Title of Post')
post.title = 'New Title of Post' 
#=> The post updated to new title is 'New Title of Post'

Or using the update method:
post = Post.find_by(title: 'Title of Post')
post.update(title: 'New Title of Post')
Delete a Post
We can remove a Post from the database, like so:
post = Post.find_by(title: 'Title of Post')
In the next step, we'll add 4 functions are: Create, Read, Update and Delete a Post for application.

Creating CRUD Post for Blog

We'll create Post Controller with 7 RESTful actions and related views for Post by scaffold_controller generator:
rails generate scaffold_controller Post title:string content:text

This command generates files as below:
Running via Spring preloader in process 12505
      create  app/controllers/posts_controller.rb
      invoke  erb
      create    app/views/posts
      create    app/views/posts/index.html.erb
      create    app/views/posts/edit.html.erb
      create    app/views/posts/show.html.erb
      create    app/views/posts/new.html.erb
      create    app/views/posts/_form.html.erb
      invoke  test_unit
      create    test/controllers/posts_controller_test.rb
      create    test/system/posts_test.rb
      invoke  helper
      create    app/helpers/posts_helper.rb
      invoke    test_unit
      invoke  jbuilder
      create    app/views/posts/index.json.jbuilder
      create    app/views/posts/show.json.jbuilder
      create    app/views/posts/_post.json.jbuilder

Focus on files:
  • Controller: app/controllers/posts_controller.rb
  • Views files in folder: app/views/posts
Open posts_controller.rb file, you can see 7 RESTful actions includes:
  • index
  • new
  • create
  • show
  • edit
  • update
  • destroy
Add routes for Post. By Rails convention, we can use resources to quickly declare 7 RESTful actions routes:
Rails.application.routes.draw do
  resources :posts

Check routes of posts by:
rails routes | grep posts

You can see:
rails routes | grep posts
     posts GET    /posts(.:format)                posts#index
           POST   /posts(.:format)                posts#create
  new_post GET    /posts/new(.:format)            posts#new
 edit_post GET    /posts/:id/edit(.:format)       posts#edit
      post GET    /posts/:id(.:format)            posts#show
           PATCH  /posts/:id(.:format)            posts#update
           PUT    /posts/:id(.:format)            posts#update
           DELETE /posts/:id(.:format)            posts#destroy

Yeah, done!
Now can open the brower and access to http://localhost:3000/posts to do CRUD actions for Post.


In this article, I already guide you about how to create a Active Record Model, Controller and related Views. Learn about how to quickly create CRUD Post in Blog application.
In the next article, I'll going to share with you about using Bootstrap library to make UI look better.