Exploring Ruby on Rails
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.
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?
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 end
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?
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 end
class BlogPost < ActiveRecord::Base has_many :blog_comments, :order => "date" end
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?
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 end
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.
Getting Started with DevOps - Including New Data on IT Performance from Puppet Labs 2015 State of DevOps Report
August 27, 2015
12:00 PM CDT
DevOps represents a profound change from the way most IT departments have traditionally worked: from siloed teams and high-anxiety releases to everyone collaborating on uneventful and more frequent releases of higher-quality code. It doesn't matter how large or small an organization is, or even whether it's historically slow moving or risk averse — there are ways to adopt DevOps sanely, and get measurable results in just weeks.
Free to Linux Journal readers.Register Now!
|Secure Server Deployments in Hostile Territory, Part II||Jul 29, 2015|
|Hacking a Safe with Bash||Jul 28, 2015|
|KDE Reveals Plasma Mobile||Jul 28, 2015|
|Huge Package Overhaul for Debian and Ubuntu||Jul 23, 2015|
|diff -u: What's New in Kernel Development||Jul 22, 2015|
|Shashlik - a Tasty New Android Simulator||Jul 21, 2015|
- Secure Server Deployments in Hostile Territory, Part II
- Hacking a Safe with Bash
- Huge Package Overhaul for Debian and Ubuntu
- KDE Reveals Plasma Mobile
- The Controversy Behind Canonical's Intellectual Property Policy
- Shashlik - a Tasty New Android Simulator
- Home Automation with Raspberry Pi
- Embed Linux in Monitoring and Control Systems
- diff -u: What's New in Kernel Development
- General Relativity in Python