Active Record CRUD Operations

Okechukwu Uneze
2 min readDec 2, 2020

--

Active Records provide an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. This strategy allows simple designs and straight forward mappings between database tables and application objects.

Given a migration file called CreateBooks and a class called Book. lets explore how some CRUD commands interreact with database and how to implement it.

class CreateBooks < ActiveRecord::Migration[5.2]
def change
create_table :books do |t|
t.string :title
t.integer :edition
t.string :author
t.integer :isbn
end
end
end
class Book < ActiveRecord::Base
end

CRUD Operations

Create (.new, .save, .Create)

#Create  
.new (makes an instance of the book)
newbook = Book.new(title: "title", edition: "2", author: "Author", isnb: 1234567895)
.save (saves the instance to the database to make it persistent)
newbook.save
.create (Does what .save and .new in a single line)
newbook = Book.create(title: "title2", edition: "2", author: "Meme", isnb: 1234588895)

Read (.all, .first, .last, .count, .order, find_by, .where)

#Read
#.all (return all object of a class or records in a table)
Book.all (returns all object class or records of book in table)
.first (picks the first record in table)
Book.first
.last (picks the last record in table)
Book.last
.count (counts the number of records and returns a number)
Book.count (returns the size of record)
.order (orders by ASC OR DESC)
Book.order(title: :DESC)
.find_by (will retrieve a single record that first matches)
Book.find_by(id: 1) (retrieves a record with id equal to 1)
.where (similar to find_by but will return all records that match give attribute)
Book.where("edition > 1") (retrieves all records that above 1 edition)

Update (.update, .update_all)

#Update
.update (updates an instance or a single record with matching attribute)
to_update = Book.find_by(title: "Seven Star")
to_update.update(title: "Nine Stars")

.update_all (updates all records with attribute)
Book.update_all(title: "All book titles are now this")

Delete (.destroy, .destroy_by, .destroy_all)

#Delete
.destroy (deletes a single record retrieved by find)
Book.find(id: 1).destroy
.destroy_by (deletes multiple records with matching attribute)
Book.destroy_by(title: "Pokemon")
.destroy_all (deletes all records without dropping the table.)
Book.destroy_all

Finally we reach the end of our journey and if which to go further and learn more go to DEVHINTS.IO for Active Record basics click HERE and for more tutorial click here and most importantly for Methods click HERE.

--

--