[Rails] Common CRUD methods

Tags
Rails
Engineering
Created
Oct 20, 2023 11:41 PM
Edited
Oct 20, 2023
Description
create/new/save/find_by/where/update/update_all/destroy

Create

Use create

user = User.create(name: "David", occupation: "Code Artist")

Use new and save

user = User.new
user.name = "David"
user.occupation = "Code Artist"
user.save

Read

Use find_by

This is useful and should be used to find only one record by the query.
# return the first user named David
david = User.find_by(name: 'David')

Use where

It returns an array of records.
# find all users named David who are Code Artists and sort by created_at in reverse chronological order
users = User.where(name: 'David', occupation: 'Code Artist').order(created_at: :desc)

Update

Use save

user = User.find_by(name: 'David')
user.name = 'Dave'
user.save

Use update

user = User.find_by(name: 'David')
user.update(name: 'Dave')
Using update will let failure pass silently. So it should be avoided.
Instead use update!.
user = User.find_by(name: 'David')
user.update(name: 'Dave')

Use update_all

Update several records at the same time.
User.update_all "max_login_attempts = 3, must_change_password = 'true'"

use update_columns

It does not trigger callbacks!

Delete

Dangerous operation!

Use destroy

user = User.find_by(name: 'David')
user.destroy

Use destroy_by

# find and delete all users named David
User.destroy_by(name: 'David')

Use destroy_all

# delete all users
User.destroy_all

Related Articles