Skip to Content
Ruby on Rails® for Microsoft Developers
book

Ruby on Rails® for Microsoft Developers

by Antonio Cangiano
April 2009
Intermediate to advanced content levelIntermediate to advanced
479 pages
12h 55m
English
Wrox
Content preview from Ruby on Rails® for Microsoft Developers

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Michael Hartl

Publisher Resources

ISBN: 9780470374955Purchase book