Exploring Ruby on Rails

A discussion about the Rails framework, how to build with it and the benefits of Ruby.
The Model

LJ: What's the first step with Rails? What are the first steps to turning some concept into code?

DF: That's a good question, because it brings up an important point about Rails that might be foreign to you if you're coming to Rails from a different framework or a different programming environment. There's a lot of code generation and a lot of the boilerplate code is generated or already exists. So, the first step with Rails is to run the rails command with the name of your application in the directory where you'd like to serve the application. For example, enter

~ > cd /var/www/htdocs/www.mysite.com && rails mycoolwebapp

and boom, this whole hierarchy is created for you.

LJ: Then what?

DF: There are a few main directories in this hierarchy that you will be spending most of your time in as a Rails application developer. The main directory is called app, and it's where your Web application will go.

LJ: So, I can imagine you might have a table representing posts to your blog, something like

create table blog_posts (
  id serial,
  post text,
  created_on timestamp,
  primary key (id)

How do you go about getting a handle on that table in Rails?

DF: After you create your application, you would generate a model called BlogPost.

LJ: Rails is pretty big on MVC, huh?

DF: Definitely; the whole framework (see Figure 1) is based on this paradigm.

Figure 1. The Rails Framework

LJ: So how do you generate this model?

DF: First, and this is really the only configuration step in Rails, you'd edit the ./config/database.yml file to reflect your database of choice--MySQL, PostgreSQL, SQLite, whatever. Basically this is username and password stuff. Next, there's a script called generate in the script directory. You give this script one argument for what type of object you want to generate, for example model or controller, and a second argument for the name of the object you are generating. In our example it would be:

~ > ./script/generate model BlogPost

LJ: Hmmm. Let me get this straight: you ran the rails command, which is itself a code generator, initially to populate a directory hierarchy with a bunch of stuff in it. And then one of those files, the generate" script, is used to generate more code for this specific application?

DF: Correct.

LJ: How did you configure the table to model-class mapping?

DF: You don't. Basically the class that rails generates is totally empty. It will look something like this

class BlogPost < ActiveRecord::Base

Because this class inherits from ActiveRecord::Base, it knows how to find its table in the database at runtime.

LJ: But we were talking about a table named "blog_posts"?

DF: Right, and it's named--this another important point that you bring up--it's named after what it contains: blog_posts, plural. And the model that you generate for that table is called BlogPost, singular. Rails has a smart Inflector class that does all this translation, but you can override it if you want.

LJ: I see Rails knows English better than I do. Your class is empty, so how do you configure the database to instance-method mapping?

DF: Again, you don't; ActiveRecord::Base handles that for you. It dynamically responds to methods at runtime, so if you call the method category on an instance of BlogPost, which, of course, represents a single row of the blog_posts table, it knows how to get that column. It knows how to look up the field "category" from that row.

LJ: What if you altered your blog_posts table, say you added a column, something such as the time the post was entered?

DF: If you followed convention and added a field named created_on to the blog_posts table, you'd get a bunch of stuff for free. First, any field in the table automatically has both getter and setter methods dynamically determined at runtime, even if the column is added later. Second, certain column names have special meaning to Rails, and created_on is one of those. A column with that name is handled automatically by inserting the creation time of the row as the transaction time at which it was created.

LJ: How do you know which column names are special?

DF: You'll want to read the API and, failing that, check out the mailing list.

LJ: And these automatic methods to access the table columns, do they return strings because they are so generic?

DF: Nope. Rails inspects the database schema and maps the columns to the appropriate types. So an int comes back as a Ruby Fixnum, a timestamp comes back as a Ruby Time object and so on.

LJ: You still haven't talked about writing any code.

DF: True. Nothing so far requires any [code] to be written.

LJ: Well, your database is pretty boring at this point; you've got only one table. How does Rails handle relationships between tables?

DF: In my opinion, this is where the real magic of ActiveRecord starts. Reflecting on the database to give a model-class getters and setters is pretty cool, but handling inter-table relationships intelligently goes to another level. Comments in a blog are a great example of this. Normally, a blog post has several comments associated with it, assuming your readers aren't too lazy to post them. Likewise, a comment always belongs to a blog post. In the database, then, a common way to implement this is to use a foreign key in one of the tables. For instance, my blog_comments table has a column labeled blog_post_id, because ActiveRecord understands this naming convention. The only other thing I had to do to connect my BlogPost model with my BlogComment model was add two lines of code, one to each of the models:

class BlogComment < ActiveRecord::Base
  belongs_to :blog_post


class BlogPost < ActiveRecord::Base
  has_many :blog_comments, :order => "date"

This, of course, assumes a some schema such as this one:

create table blog_comments (
  id serial,
  comment text,
  blog_posts_id int,
  primary key (id),
  foreign key (blog_posts_id) references blog_posts (id)

After I did this and played with the code a little bit, I realized how cool it was. Automatically an instance of BlogPost had a new method called comments that would yield an array of the comments whose foreign key, blog_post_id, matched the ID of the BlogPost instance. The same was true of a BlogComment instance; a method named post provided the BlogPost instance associated with that comment via the foreign key.

LJ: So Rails dynamically generates join selects if it has been told two tables are related?

DF: Yep.

LJ: That's almost like configuration.

DF: Well, true, but because it's done in a fully fledged programming language such as Ruby instead of a data language such as XML, it can do so much more. For instance, if we're working with a database that didn't support foreign keys, such as SQLite, and you defined the relationship like this

class BlogPost < ActiveRecord::Base
  has_many :blog_comments, :order => "date", :dependent => true

Rails would handle cascading delete for you. That is, deleting a BlogPost would result in all its associated BlogComments being deleted too, even though the underlying database may not enforce foreign keys or cascading deletes.

LJ: But surely well-designed classes could grok XML that somehow dictated cascading deletes?

DF: Yeah, that's true, but it's really nice for the programmer to be able to keep everything--model, view, controller--all in one language. In Rails you don't have to split out state and behavior into separate files; you can describe it all in one file using the same language. Plus, in practice, only a few of these configuration steps even need to be taken, because Rails model-objects are designed to reflect on the database at runtime. It's not an exaggeration to say that your entire controller-class could end up being shorter than a single XML configuration file.



Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Interesting article

Anonymous's picture

Thank you for the interesting article. We have considering using Ruby for various portions of our web to print solution.

Exploring Ruby on Rails

securenext's picture

Ruby on Rails or RoR, is an open source web application framework for the Ruby programming language.

We build quality Ruby On Rails web applications for startups and established businesses since early 2006. We focus on the core idea, perfect the interface, suggest innovative features and deliver; we help your company succeed faster by using the best technologies available.

Secure Next is a software technology corporation that develops, manufactures, and supports a wide range of software and web development projects. Headquartered in Fresno, California, USA, and its offshore in Chennai, India, we rock on every single projects we develop and venture into upcoming technology with a vision of agile web development & customer satisfaction.

Thus, we want to make people feel informed and involved, committing quality and timeliness and ready to flourish using latest technology. website: http://www.rordevelopers.com & http://www.securenext.com


jaysmith's picture

really liked the Q&A approach. This article was just what I needed as a newbie who is just getting started with RonR.

Thinking about ruby

Dinesh Sharma's picture

I think that ruby on Rails is an interesting language as well as faster then others but little bit confused that will i be able to develop any kind of application ?

Ruby - For Professionals

Computer Service Bonn's picture

Ruby reminds me on the forecast of gartner, that till 2010 there will be 40% less employment in information technology. The forecast bases on the fact, that productivity in IT increases dramatically. Ruby demonstrates another highly productive environment. It is not neccessary to learn anything, neither design pattern nor programming languages. For Doug Fales who is very experienced in Java, Ruby is a nice trip. But I would not begin with it.

Ruby on Rails Interview

JC's picture

Good job & very interesting!

I really liked the Q&A approach. This article was just what I needed as a newbie who is just getting started with RonR.

My development teams are JAVA and Coldfusion based. They are reluctant to consider RonR, but I am very impressed and will continue down this road.