Home arrow Ruby-on-Rails arrow Rails Active Record and CRUD Functions

Rails Active Record and CRUD Functions

In this second part of a three-part article series on the Active Record of Rails, you'll learn the basics, such as the create, read, update, and delete functions. This article is excerpted from chapter four of the book Beginning Rails: From Novice to Professional, written by Jeffrey Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).

Author Info:
By: Apress Publishing
Rating: 5 stars5 stars5 stars5 stars5 stars / 5
January 13, 2010
  1. · Rails Active Record and CRUD Functions
  2. · Using the create Constructor
  3. · Reading (Finding) Records
  4. · Finding All Records

print this article

Rails Active Record and CRUD Functions
(Page 1 of 4 )

Active Record Basics: CRUD

Active Record is a big topic, so we’re going to start with the basics. We already alluded to the so-called big four earlier, but here they are again: create, read, update, and delete, affectionately known as CRUD. In one way or another, most of what you do with Active Record in particular, and with databases in general, relates to CRUD. Rails has really embraced CRUD as a design technique and as a way to simplify the modeling process. It’s no surprise then that we’re going to take an in-depth look at how to do CRUD with Active Record.

We’ll build on the events application we started in the previous chapter. Although our application doesn’t do very much yet, it’s at a stage where it will be easy to demonstrate these concepts in a more concrete fashion.

We’ll be doing this whole section on the console, so keep it open as you work, and feel free to experiment as much as you want. The more experimentation you do, the deeper your understanding will be.

Creating New Records

We’re going to start by creating a new event in the database so we have something to work with. There are a few different ways to create new model objects, but they’re all variations on the same theme. We’ll show you how each of them works and explain the often subtle differences between them as we go.

Using the new Constructor

The most basic way to create a new model object is with thenewconstructor. If you read the crash-course sidebar on Ruby classes, you’re sure to recognize it. If you didn’t, then it’s enough that you knownewis the usual way to create new objects of any type. Active Record classes are no different. Let’s try it now.

>> event = Event.new
=> #<Event:0x23a98e8 @new_record=true, @attributes={"title"=>nil, "url"=>nil, "occurs_on"=>nil, "description"=>nil, "location"=>nil}>

All we’re doing here is creating a newEventobject and storing it in the local variable,event. True to form, the console responds with the return value of method, which, in this case, is a string representation of the model object. It may look a little funny, but this is what all Ruby objects look like when we inspect them. You can see from the response that there are a couple instance variables set:@new_record, which tells us that this is a new object that has not yet been persisted to the database, and@attributes, which contains a hash of the attributes that Active Record garnered by reflecting on the columns in the table. Of course, we can confirm either of these by asking the object.

>> event.new_record?
=> true
>> event.attributes
=> {"title"=>nil, "url"=>nil, "occurs_on"=>nil, "description"=>nil, "location"=>nil}

Here, we’re using reader methods, which read and return the value of the attribute in question. Since this is a brand-new record and we haven’t given it any information, all our attributes arenil, which means they have no values. Let’s remedy that now using (what else?) writer methods.

>> event.title = 'RailsConf'
=> "RailsConf"

>> event.location = 'Portland, Oregon'
=> "Portland, Oregon"

>> event.occurs_on = '2007-05-17'
=> "2007-05-17"

>> event.url = 'http://railsconf.org'
=> "http://railsconf.org"

>> event.description = "An awesome gay 'ole time with other Rails programmers."
=> "An awesome gay 'ole time with other Rails programmers."

Note  A return ofnilalways represents “nothing.” It is a helpful little object that stands in the place of nothingness. If we ask an object for something and it returnsfalse, then false is something so it’s not a helpful representation. As a nerdy fact, in logics, false and true are equal and opposite values, but they are values in the end. The same is true of zero (0). The number 0 is not truly “nothing.” It is an actual
representation of an abstract nothing, but it is still something. That’s why in programming we havenil(ornull in other languages).

Now when we inspect ourEventobject, we can see that it has attributes.

>> event
=> #<Event:0x23a98e8 @new_record=true, @attributes={"title"=>"RailsConf",
 "url"=>"http://railsconf.com", "occurs_on"=>"2007-05-17", "description"=>"An
awesome gay 'ole time with other Rails programmers.", "location"=>"Portland, Oregon"}>

We still haven’t written a new record. If you were to look at theeventstable in the database, it would still be empty. (If you squint really hard at the preceding object inspection string, you’ll notice the@new_recordvariable is stilltrue, and that noidhas been assigned yet.) That’s because we haven’t yet saved the object to the database. Fortunately, saving an Active Record object couldn’t be any easier.

>> event.save
=> true

When you save a new record, a SQLINSERTstatement is constructed behind the scenes. If theINSERTwas successful, thesaveoperation returnstrue; if it fails,savereturnsfalse. We can ask for acountof the number of rows in the table just to be sure that a record was created.

>> Event.count
=> 1

Sure enough, we have our first event! You’ve got to admit, that was pretty easy. (Now, you might have created some events already during the scaffolding session. If so, don’t be surprised if you have more than one event already.) Additionally, if we ask the event whether or not it is anew_record?, it will respond withfalse. Since it’s saved, it’s not “new” anymore.

>> event.new_record?
=> false

Let’s create another event. This time we’ll omit all the chatter from the console so you can get a better sense of how the process plays out. We create a new object and place it in a variable, we set the object’s attributes, and finally, we save the record. Note that while we’re using the local variableevent to hold our object, it can be anything you want. Usually, you’ll use a variable that indicates the type of object you’re creating, likeevent, or if you prefer shorthand, juste.

>> event = Event.new

>> event.title       = "Jeff's Birthday Party"
>> event.location    = "Flaming Moe's"
>> event.url         = 'http://quotedprintable.com'
>> event.description = "Bring gifts to *me*!"
>> event.occurs_on   = '2007-10-13'

>> event.save

Note  While writer methods look like assignments, they’re really methods in disguise. event.title = 'something'is the functional equivalent ofevent.title=('something'), wheretitle=()is the method. Ruby provides a little syntactic sugar to make writers look more natural.

Now we’re rolling! We’ve already created two events and haven’t had to write a lick of SQL. Given how easy this is, you might be surprised that we can do it in even fewer steps, but we can. Instead of setting each attribute on its own line, we can pass all of them tonewat once. Here’s how we could rewrite the preceding process of creating a new record in fewer lines of code:

event = Event.new(:title       => "Jeff's Birthday Party",
                  :location    => "Flaming Moe's")
                  :url         => "
:description => "Bring gifts to *me*!",
                  :occurs_on   => "2007-10-13",

Not bad, but we can do even better. Thenew constructor creates a new object, but it’s our responsibility to save it. If we forget to save the object, it will never get written to the database.

blog comments powered by Disqus

- Ruby-on-Rails Faces Second Security Flaw in ...
- Ruby 2.0 Prepped for February 2013 Release
- Why LinkedIn Switched from Ruby on Rails
- Adding Style with Action Pack
- Handling HTML in Templates with Action Pack
- Filters, Controllers and Helpers in Action P...
- Action Pack and Controller Filters
- Action Pack Categories and Events
- Logging Out, Events and Templates with Actio...
- Action Pack Sessions and Architecture
- More on Action Pack Partial Templates
- Action Pack Partial Templates
- Displaying Error Messages with the Action Pa...
- Action Pack Request Parameters
- Creating an Action Pack Registration Form

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials