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.
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:
user = User.create(name: "David", occupation: "Code Artist")
Using the new method, an object can be instantiated without being saved:
user = User.new
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:
user = User.new do |u|