Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Active Record Models

CRUD with Active Record

Learn the Active Record CRUD methods: new, create, save, find, update, destroy, bang methods and change tracking. Includes a runnable stand-in with timestamps, dirty tracking and errors.

CRUD stands for Create, Read, Update and Delete, the four things every app does with data. Active Record gives each one a clear method, and almost every controller action you will write is built from them. This lesson walks through the methods, the difference between the plain and the bang (!) versions, and how Active Record remembers what changed.

The real methods run SQL against a database, so the Rails snippets are read-only. A runnable stand-in near the end reproduces the behaviour (timestamps, change tracking, save returning false) with plain Ruby so you can experiment.

Create

There are two ways to make a record. new builds an object in memory; save writes it. create does both at once:

Ruby
# read-only: rails console
article = Article.new(title: "Hello", body: "First post")
article.persisted?    # => false
article.save          # => true (INSERT executed)
article.persisted?    # => true
article.id            # => 1

Article.create(title: "Second", body: "More text")      # build + save
Article.create([{ title: "A" }, { title: "B" }])         # several at once

Active Record fills id, created_at and updated_at for you. If a validation fails (see validations), save returns false and nothing is written; create returns the unsaved object. In a controller, new plus save is the usual pattern because you branch on the result, as in controllers and actions.

Read

Ruby
# read-only
Article.all                      # every row (a lazy relation)
Article.first                    # first by primary key
Article.last
Article.find(3)                  # by id; raises ActiveRecord::RecordNotFound
Article.find_by(title: "Hello")  # first match or nil
Article.where(published: true)   # a relation of matches
Article.count
Article.exists?(title: "Hello")

find raises when the record is missing, and Rails turns that exception into a 404 page in production. That is what you want for a "show" page. find_by returns nil, which suits cases where absence is normal. Longer queries are covered in the query interface lesson.

Update

Ruby
# read-only
article = Article.find(1)
article.title = "New title"
article.save                          # writes only the changed column

article.update(title: "Newer", published: true)       # assign + save, returns true/false
article.update_column(:views, 10)     # skips validations and callbacks, no updated_at
Article.where(published: false).update_all(published: true)   # one SQL UPDATE, skips callbacks
article.touch                         # only bumps updated_at
article.increment!(:views)

Pick the method by what you need. update runs validations and callbacks and is the safe default. update_column and update_all are fast and bypass the model's rules, so use them deliberately.

Delete

Ruby
# read-only
article.destroy                       # runs callbacks, deletes the row, freezes the object
Article.destroy_by(published: false)  # destroys each match (with callbacks)
article.delete                        # direct SQL DELETE, no callbacks
Article.delete_all                    # one DELETE statement

destroy is the default. It also triggers dependent: :destroy on associations (associations). delete skips all that, so related rows can be left behind.

Bang methods

Most methods have a bang twin: save!, create!, update!, destroy!. The plain version returns false on failure; the bang version raises an exception (ActiveRecord::RecordInvalid or RecordNotDestroyed).

Ruby
# read-only
if article.save
  redirect_to article
else
  render :edit, status: :unprocessable_entity
end

# in seeds, scripts, jobs: fail loudly
Article.create!(title: "Seed data", body: "...")

Use the plain form when the user can fix the problem (forms) and the bang form where a failure is a bug (seed files, background jobs, scripts).

Change tracking (dirty attributes)

Active Record remembers the original values after loading, so you can ask what changed before saving. This is also how save writes only the changed columns.

Ruby
# read-only
article = Article.find(1)
article.title = "Edited"
article.changed?            # => true
article.changes             # => { "title" => ["Hello", "Edited"] }
article.title_changed?      # => true
article.title_was           # => "Hello"
article.save
article.saved_change_to_title?   # => true  (after save)

Stand-in: CRUD with timestamps and dirty tracking

This stand-in is a small model base class with new, save (returning true or false), update, destroy, timestamps and changes. It uses a fixed clock so the output is the same on every run.

Ruby Stand-in: save, update, changes and destroy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Look at each result: save returns false and fills errors when the title is blank, changes lists old and new values until a save clears them, and updated_at moves only when something changed. Real Active Record behaves the same way, with a database behind it.

Common mistakes

  • Using update_all, delete or update_column and then wondering why callbacks and validations did not run.
  • Ignoring the return value of save, so a failed save looks like a success. Check it, or use the bang version.
  • Calling find for something that can legitimately be missing; use find_by and handle nil.
  • Mass-assigning raw params. Always filter with strong parameters.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does article.save return when a validation fails?

    The plain save returns false and does not write; save! would raise instead.
  2. 2. Which method returns nil instead of raising when no record matches?

    find raises RecordNotFound; find_by returns the first match or nil.
  3. 3. Which method skips validations and callbacks and updates many rows with one SQL statement?

    update_all issues one UPDATE directly and bypasses the model's rules.
  4. 4. After article.title = "Edited", what does article.changed? return before saving?

    Active Record tracks unsaved attribute changes until the record is saved.

Summary

  • new + save or create insert a row; find, find_by, where read; update changes; destroy deletes.
  • Plain methods return true/false; bang methods (save!, create!) raise on failure.
  • update_all, update_column and delete are fast but skip validations and callbacks.
  • Active Record tracks changes (changed?, changes, title_was) and writes only changed columns.
  • Always check the result of save or use the bang form where failure is a bug.

Next: Attributes, Types and Enums