7.4. CRUD Operations

One thing should be clear by now. ActiveRecord really shines when it comes to simplifying the basic operations for creating, reading, updating, and deleting data. Let's systematically review the methods that are available when you want to perform CRUD (create, read, update, delete) operations.

7.4.1. Create

Because a table is represented by a model class, and its rows by instances of that class, inserting new records is as easy as creating a new model object and then saving it.

Assume that you have a model that was generated by the following command:

ruby script/generate model Book title:string author:string publisher:string
pages:integer isbn:string description:text

NOTE

This is a long chapter with a lot of reference-like content, so you don't have to follow along and type all code, except when explicitly asked to do so. If you do wish to type along throughout, remember that a model generation must always be followed by running migrations (rake db:migrate), so that it can actually create the table in the database.

When you create an empty object, all of its attributes that represent columns will be set to nil:

C:\projects\chapter7> ruby script/generate model Book title:string author:string
publisher:string pages:integer isbn:string description:text
>> my_book = Book.new
=> #<Book id: nil, title: nil, author: nil, publisher: nil, pages: nil, isbn: nil,
description: nil, created_at: nil, updated_at: nil>

As a reminder, the >> and => tokens respectively represent ...

Get Ruby on Rails® for Microsoft Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.