Home arrow Ruby-on-Rails arrow Working with a Database: Active Record
RUBY-ON-RAILS

Working with a Database: Active Record


If you're interested in learning more about the Rails framework, keep reading. This three-part article series takes an in-depth look at one of its more important aspects, the Active Record. 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 / 6
January 12, 2010
TABLE OF CONTENTS:
  1. · Working with a Database: Active Record
  2. · What About SQL?
  3. · Active Record Conventions
  4. · Introducing the Console

print this article
SEARCH DEVARTICLES

Working with a Database: Active Record
(Page 1 of 4 )

In the previous chapter, we took a whirlwind tour through creating a basic Rails application using the built-in scaffolding feature. We sketched out a basic model for our sample application, an event manager, and created the project databases. We used the built-in web server to deploy the application locally, and practiced adding and managing events from the web browser. In this chapter, weíre going to take a more in-depth look at how things work, starting with what is arguably the most important part of Rails: Active Record.

You might recall from Chapter 1 that Active Record is the Ruby library that handles database abstraction and interaction for Rails. In fact, whether you realized it or not, in the previous chapter, all the access to the databaseóadding, editing, and deleting eventsóhappened through the magic of Active Record.

Active Record is the name given to the object-relational mapping library that ships with Rails. If youíre not sure what exactly object-relational mapping is, donít worry. By the end of this chapter, you will know. For now, itís best if you think of Active Record as being an intermediary that sits between your code and your database, allowing you to work with data effectively and naturally. When you use Active Record, you communicate with your database using pure Ruby code. Active Record translates the Ruby you write into a language that databases can understand.

The purpose of this chapter is to teach you how to use Active Record to talk to your database and perform basic operations. Weíll introduce you to the concepts you need to know about communicating with databases and object-relational mapping. Then weíll take a look at Active Record and walk you through the techniques you need to know to effectively work with a database from Rails. If you donít have a lot of database experience under your belt, you neednít worry. Youíll find that working with databases through Active Record is a painless and even enjoyable experience. If youíre an experienced database guru, youíll find that Active Record is an intelligent and efficient way to perform database operations without the need for low-level database-specific commands.

Introducing Active Record: Object-Relational Mapping on Rails

The key feature of Active Record is that it maps tables to classes, table rows to objects, and table columns to object attributes. This practice is commonly known as object-relational mapping, or ORM for short. To be sure, Active Record isnít the only ORM in existence, but it may well be the easiest to use of the bunch.

One of the reasons that Active Record is so easy to use is that there is almost no configuration required to have it map a table to a class. You just need to create a Ruby class thatís named after the table you want to map and extend the Active RecordBaseclass.

class Event < ActiveRecord::Base
end

Notice the part that reads< ActiveRecord::Base. That less-than sign indicates that the class on the left is a subclass of the one on the right. In Ruby, when you extend a class like this, you automatically gain access to all the functionality in the parent class. Thereís a lot of code in theActiveRecord::Baseclass, but we donít need to look at it. Our class merely extends it, and our work is finished.

Assuming Active Record knows how to find our database and that we have a table calledevents(note that the table name is plural while the class name is singular), the table is automatically mapped. If oureventstable contained the fieldstitle,location, andoccurs_on, we could do this:

event = Event.new

event.title = "BBQ at Hampton's House" event.location = "471 230 King Street" event.occurs_on = "2006-10-13"

event.save

Those five lines would write a new record to theeventstable. Thatís a lot of ability we gained just by the simple act of subclassing! And thatís what we mean when we say that Active Record is easy to use. Notice how the tableís fields (title,location, andoccurs_on) can be read and written to using methods on the object we created (event). And we didnít need to tell Active Record what our fields were named, or even that we had any fields. It figured that out all on its own. Of course, Active Record doesnít just let you create new records. It can also read, update, and delete records, plus a lot more.

Active Record is database-agnostic, so it doesnít care which database software you use, and it supports nearly every database out there. Since itís a high-level abstraction, the code you write remains the same no matter which database youíre using. For the record (no pun intended), weíll be using MySQL. As explained in Chapter 2, MySQL is open source, easy to use, fast, and arguably the most popular database used for Rails development. (Along with the MySQL site,http://mysql.com, the Wikipedia entry on MySQL is an excellent resource:http://en.wikipedia.org/wiki/Mysql.)


blog comments powered by Disqus
RUBY-ON-RAILS ARTICLES

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

Developer Shed Affiliates

 




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