Explained: learning Ruby on Rails (Part 2)

If you followed along in , you will have downloaded and installed Netbeans 6 to get a complete Ruby development environment. You should also have prototyped a web design idea, added some dynamic code to it, and got cosy with Ruby by implementing a small standalone application.

In this article, we’ll learn a few more techniques to help you build the next big thing for the web.

Back to your website

By now you’ve probably picked up enough techniques to build basic HTML templates using rails layouts and helper functions. With any luck, you’ll have explored the rails MVC framework and seen how controllers link to views and public URLs.

While this may be sufficient for your prototype, the next step to learning the full framework is to start working with a database. If you already have a database server installed on your machine, create a new database for your project. Otherwise, download and install MySQL, Postgres or SQL Server Express. Configure your database by editing the config/database.yml file in your rails application. Refer to this quick database setup guide for the exact syntax.

If you’ve worked with an object-relational mapping system before (such as Hibernate or NHibernate), the concepts and principles of ActiveRecord will seem very familiar to you. If not, reading the short “problem description” section on wikipedia’s ORM article will give you an overview of how ActiveRecord differs from (for example) the old PHP or VB methods of accessing a database from your code.

Migrate your database

Migrating your database between versions

For brand new rails projects, you can build your database schema incrementally, using Migrations. This feature allows you to use Ruby to create table definitions that can be run against any database server. Create and run your first migration by right-clicking on your project and selecting ‘Generate…’. Choose ‘migration’ from the drop-down list and enter an appropriate name such as ‘add_initial_tables’. If you prefer the command line, then running this command (from your rails app directory) will achieve the same thing:

./script/generate migration add_initial_tables

This will generate a class in your project under db/migrate named something like 001_add_initial_tables.rb. (The exact number in the file name will vary according to the version of rails you are running). Open this class and you’ll see two simple method definitions; “up” and “down”. You write some simple ruby code that will create a table using the create_table function. In the example below we create a table to store our collection of flowers:

class AddANewTable < ActiveRecord::Migration
  def self.up
    create_table :flowers do |table|
      table.column :name, :string
      table.column :latin_name, :string
      table.column :color,  :string, :null => false
      table.column :needs_water, :boolean, :default => true, :null => false
    end
  end

  def self.down
    drop_table :flowers
  end
end 

The migration wiki page has the full background information on managing your database schema with migrations. For now, we’ll just get up and running with a single table and you can create an elaborate schema as an exercise. To ‘run’ your migrations, right-click your project in Netbeans and select Migrate Database -> “To Current Version”. If you have configured your database connection correctly, you should see some output describing your table of flowers being created.

To add new rows to the database, generate a model class that will map to this table. (Right-click your project, select ‘Generate…’, choose ‘model’ from the drop-down and enter ‘Flower’ in the text box). You can now create new rows from any of your controller classes simply by calling:

Flower.create(:name => 'Rose', :color => 'red', :needs_water => true)

How to use all of the features of ActiveRecord is beyond the scope of this article but it’s worth noting that it makes simple tasks very easy and a lot of difficult tasks very doable. The ActiveRecord reference documentation builds on our introduction and immerses you in the phenomenal power of Rails. For me, ActiveRecord is the shining star of the Rails framework.

Put your users first

Rails also make it very easy to get a full user management system up and running. While there is no built-in user framework out-of-the-box, two open source rails plugins are particularly popular.

Acts_as_authenticated introduces the concept of a User object to your project with minimal effort. It generates a basic user model, a controller, some basic views, a database migration and tests. To install plugins, it’s necessary to use the command-line. You install the plugin by running this command in your rails project directory:

./script/plugin install \

http://svn.techno-weenie.net/projects/plugins/acts_as_authenticated

Once the plugin has downloaded, you can generate all the relevant classes with this command:

./script/generate authenticated user account

Acts_as_authenticated is a great starting point to learn the various hooks into rails controllers. Once you’ve got your sign-up and sign-in pages customized to how you like them, you might need more sophisticated user checking. Look at the authorization plugin for help determining which pages and functions your users have access to.

No need to be afraid: Ruby refactoring

It’s still early days when it comes to tool support for ruby and rails. However, one of the best kept secrets of the 6.1 release of netbeans is the support for refactoring ruby classes. Refactoring allows you to rename your classes, methods and variables after the event without having to do any manual find-and-replace yourself. It’s worth skimming the netbeans ruby refactoring document as the only way to access these powerful features at the moment is with keyboard shortcuts. 

Last minute checks

If you’ve been happy working with rails so far, it’s worth pausing to think about how you plan to host your final application in a production environment. While it’s important not to distract too much from your development, hosting rails applications is not always as trivial as uploading PHP files to shared hosting. It can be difficult to find good rails hosting for a variety of reasons. However, once you’re aware of the issues and can make an informed decision on what you need, the search for quality hosting becomes much easier.

Hard copy resources

The following links are to books that help you get the most from Rails, or to transition from another technology you’re already familiar with. I’ve personally made extensive use of Rails for Java Developers and Agile Web Development with Rails.

Do you have a specific book recommendation? Have you learnt Rails yourself using different techniques? Share your thoughts in the comments section below.

This entry was posted in Rails and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s