Home arrow Ruby-on-Rails arrow Page 4 - 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 / 1
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

TOOLS YOU CAN USE

advertisement
Working with a Database: Active Record - Introducing the Console
(Page 4 of 4 )

Ruby comes with a great little tool: an interactive interpreter. It’s called irb (for Interactive Ruby). Most of the time, you’ll invoke irbusing the console program that ships with Rails, but you can start up anirbsession whenever you want by typingirbat the command prompt. The advantage of the console is that it enjoys the special privilege of being integrated with your project’s environment. This means it has access and knowledge of your models (and subsequently, your database).

We’ll be using the console as a means to get inside the world of ourEventmodel and to work with it in the exact same way as our Rails application would. As you’ll see in a minute, this is a great way to showcase the capabilities of Active Record interactively.

You can execute any arbitrary Ruby code inirband do anything you might otherwise do inside your Ruby programs: set variables, evaluate conditions, and inspect objects. The only essential difference between an interactive session and a regular old Ruby program is thatirbwill echo the return value of everything it executes. This saves you from having to explicitly print the results of an evaluation. Just run the code, andirbwill print the result.

You’ll be able to tell whenever you’re inside anirbsession by looking for the double greater-than signs (>>), which indicate theirbprompt, and the arrow symbol (=>), which indicates the response.

As you continue to progress with both Ruby and Rails, you’ll find thatirbis an essential tool. Usingirb, you can play around with code and make sure it works as you expect before you write it into your programs.

Let’s load it and start to experiment with ourEventmodel. Make sure you’re inside the event manager application directory, and then type./script/consoleon your command line. This will cause theirbconsole to load with the development environment and leave you at a simple prompt, waiting for you to enter some code.

$ ./script/console
Loading development environment.
>>

If you’ve been following along with the previous chapters, then you should have a model calledEvent(inapp/models/event.rb), and you probably already entered some sample data when playing with scaffolding in the previous chapter. If not, make sure you get up to speed by reading Chapter 3 before moving on.

From the console, we can interrogate ourEvent model for information. For instance, we might ask it for its column names.

>> Event.column_names
=> ["id", "title", "location", "occurs_on", "url", "description"]

Look at that! All our columns are presented as a Ruby array (which we can tell by the fact that they are surrounded by square brackets). We got thecolumn_namesclass method courtesy of theActiveRecord::Baseclass from which ourEventclass inherits. Actually, we get a lot of methods courtesy ofActiveRecord::Base. To see just how many, we can ask.

>> Event.methods.size
=> 396

That’s a lot of methods! Don’t worry—you don’t need to memorize all 396 of them, and most of them are private to Active Record and are used internally, so you’ll never even use them. Still, it’s important, if for no other reason than to get a sense of what you get for free just by subclassing Active Record. Even though in this case,ActiveRecord::Baseis considered the superclass, it sure makes our lowlyEvent class super, doesn’t it? (Sorry, enough bad humor.)  


 A CRASH COURSE IN RUBY CLASS DESIGN

Object-oriented programming is all about objects. You create classes that encapsulate all the logic required to create an object, along with its properties and attributes, and use the class to produce new objects, each of which is a unique instance, distinct from other objects of the same class. That might sound a little abstract (and with good reason--abstraction, after all, is the name of the game), but if it helps, you can think of a class as being an object factory.

The obvious example is that of a car factory. Contained within a car factory are all the resources, tools, workers, and processes that are required to produce a shiny new car. Each car that comes off the assembly line is unique. The cars may vary in size, color, and shape, or they may not vary from each other much at all. The point is that even if two cars share the exact same attributes, they are not the same car. You certainly wouldn’t expect a change to the color of one car to affect all the others, would you? Well, in object-oriented programming, it’s not much different. The class is the factory that produces objects, which are called instances of a class. From a single factory, an infinite number of objects can be produced.

class Car
end

car1 = Car.new
car2 = Car.new

car1is aCarobject, which is to say, it’s an instance of the classCar. Each car is a different object, created by the same factory. Each object knows which class it belongs to (which factory created it), so if you’re ever in doubt, you can ask it:

car2.class #=> Car

OurCarclass doesn’t really do anything that useful--it has no attributes. So, let’s give it some. We’ll start off by giving it amake. This would be something like Toyota or Nissan. Of course, we need to define a way to read and write these attributes. We do this by creating aptly named reader and writer methods. Some object-oriented languages refer to these as getters and setters. The two sets of terms are pretty much interchangeable, but Ruby favors the former. Let’s go ahead and add a reader and writer for themakeattribute now.

class Car
  # A writer method. Sets the value of the @make attribute
  def make=(text)
    @make = text
  end

  # A reader method. Returns the value of the @make attribute
  def make
    @make
  end
end

The methods we just defined (make()andmake=()) are instance methods. This is because they can be used only on instances of the class, which is to say, the individual objects that have been created from the class. To create a new instance of theCarclass, we use thenewconstructor.

my_car = Car.new

That’s all that’s required to create a new instance of the classCarin a local variable calledmy_car. The variablemy_carcan now be considered aCarobject. Although we have a newCarobject, we haven’t yet given it amake. If we use the reader method we created to ask our car what its make is, we’ll see that it’snil.

my_car.make #=> nil

Apparently, if we want our car to have a make, we’ll have to set it. This is where the writer method comes in handy.

my_car.make = 'Toyota'

This sets the value of themakeattribute for our car toToyota. If we had otherCarobjects, their makes would remain unchanged. We’re setting the attribute only on themy_carobject. Now when we use the reader method, it confirms that themakeattribute has been updated.

my_car.make #=> 'Toyota'

Of course, you can change the value any time you want.

my_car.make = 'Mazda'

And again, if you ask yourCarobject its make, it will tell you.

my_car.make #=> 'Mazda'

That’s a simple example, but it illustrates a couple of very important points: Classes are used to create objects and objects have attributes. Every object has a unique set of attributes, different from other objects of the same class.

The reason for this crash course in Ruby class design is to illustrate the point that modeling with Active Record is a lot like modeling with standard Ruby classes. In fact, if you decided to think of Active Record as being an extension to standard Ruby classes, you wouldn’t be very far off. In practice, this fact makes using Active Record in Ruby quite natural. And since Active Record can reflect on your tables to determine which fields to map automatically, you need to define your attributes in only one place: the database. That’s DRY!  


Please check back tomorrow for the continuation of this article.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
RUBY-ON-RAILS ARTICLES

- 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
- Ruby on Rails Templates and Layouts
- Action Pack Controller Creation
- Writing an Action Pack Controller

Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 



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