[Ruby Rails Guides] Active Record Basics

Active Record Basics

This guide is an introduction to Active Record.

After reading this guide, you will know:

  • What Object Relational Mapping and Active Record are and how they are used in Rails.

  • How Active Record fits into the Model-View-Controller paradigm.

  • How to use Active Record models to manipulate data stored in a relational database.

  • Active Record schema naming conventions.

  • The concepts of database migrations, validations, and callbacks.

5 CRUD: Reading and Writing Data

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

5.1 Create

Active Record objects can be created from a hash, a block, or have their attributes manually set after creation. The new method will return a new object while create will return the object and save it to the database.

For example, given a model User with attributes of name and occupation, the create method call will create and save a new record into the database:

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

Using the new method, an object can be instantiated without being saved:

1
2
3
user = User.new
user.name = "David"
user.occupation = "Code Artist"

A call to user.save will commit the record to the database.

Finally, if a block is provided, both create and new will yield the new object to that block for initialization:

1
2
3
4
user = User.new do |u|
u.name = "David"
u.occupation = "Code Artist"
end

References

[1] The Gnar Blog - ActiveRecord’s New Takes a Block, Kid - https://blog.thegnar.co/activerecord-new-block

[2] Active Record Basics — Ruby on Rails Guides - https://guides.rubyonrails.org/active_record_basics.html