Ruby on Rails is an open source web development stack with a large developer base. Last year, Ruby on Rails reached a critical milestone with the release of Ruby on Rails version 3.0. For more information about Ruby on Rails I recommend checking out www.rubyonrails.org. You can find installation information, documentation and links to other resources on this site. This article will demonstrate how to get up and running with Ruby on Rails with help from the RailsInstaller.

Ruby on Rails greatly simplifies the process of building web applications. Melding the power of the Ruby programming language with a well-constructed MVC (Model View Controller) architecture, Ruby on Rails represents a robust architecture for building web applications. This article will demonstrate some of the basic features of the Ruby on Rails development stack and give you a pathway to start exploring it.

Installing Ruby on Rails

The first step to using Ruby on Rails begins with installation. How you install Ruby on Rails depends greatly on your development platform. If your platform is Linux or OSX, a convenient way to install Ruby on Rails is to use the Ruby Version Manager (RVM). RVM is a shell script that helps you install different version of Ruby, different Ruby Gems (components) and entire Ruby on Rails configurations. You can find information for RVM, including installation and usage documentation, at https://rvm.beginrescueend.com/.

If you are using Microsoft Windows you can use the RailsInstaller application (Figure 1) from http://railsinstaller.org/. The RailsInstaller is a simple setup program that creates a complete Ruby on Rails development environment with the following configuration:

Figure 1: Use RailsInstaller to build a Ruby on Rails development stack on Windows.
Figure 1: Use RailsInstaller to build a Ruby on Rails development stack on Windows.
  • Ruby Version 1.8.7
  • Rails Version 3.0.6
  • Git Version 1.7.3.1
  • Sqlite Version 3.7.3

The RailsInstaller also provides a set of tools known as DevKit, which you use to compile Ruby Gems that contain native extensions, i.e., written in C or C++.

The last step of the RailsInstaller will ask if you want to configure Git and SSH. I recommend you answer yes to these questions. Developers commonly deploy their web Ruby on Rails applications using hosting companies such as Engine Yard (www.engineyard.com) or Heroku (www.heroku.com). Both of these companies use Git and SSH to deploy applications. Once you have completed all of the installation steps you will be presented with a command shell (Figure 2). When this command shell opens you can configure your Rails development environment.

Figure 2: The command shell lets you configure your Rails environment.
Figure 2: The command shell lets you configure your Rails environment.

Once you are done with the RailsInstaller I recommend you install a decent text editor. For this article I will use Notepad++ with the Explorer plugin.

Building Your First Rails Application

Now that you have installed Rails and your text editor you can build your first Rails application. To bootstrap your first Rails application, open the command shell provided by the RailsInstaller. You can access this from the RailsInstaller->Command Prompt with Ruby and Rails on your Start menu.

Once you have opened the command shell, execute the following command:

rails new codemag

When you execute this command, Rails will create a new folder called codemag that will contain the directory structure for your Rails application. Figure 3 shows the output from the Rails new command.

Figure 3: There are two folders of note. The first is the app folder.
Figure 3: There are two folders of note. The first is the app folder.

Building Your First Entity

Now that you have established your project you can go to work and build something useful. For this demonstration you will construct a set of Web pages for maintaining customer records using Rails built-in generator tools. One generator provided by Rails, known as the scaffold generator, will build all the files necessary to present and maintain an entity. To execute the generator, open the command shell and execute the following command:

rails g scaffold customer 
name:string customertype_id:integer 
customerstatus:string

When you run this command, Rails will generate a number of folders and files for this entity. Figure 4 shows the output of the scaffold generator.

Figure 4: Output from generating a new entity using the built-in Rails scaffold generator.
Figure 4: Output from generating a new entity using the built-in Rails scaffold generator.

Notice that the scaffold generator creates a file in the db/migrations folder. This file, known as a database migration file, will be used to create the table for your entity. This is where you need to execute one more command, the rake command. One of the tools you will use in Ruby is rake.

Rake is used to automate a number of tasks including, but not limited to: running tests, running database migrations and running database seed operations.

Rake is used to automate a number of tasks including, but not limited to: running tests, running database migrations and running database seed operations. To create the table for the customer entity, execute the following command from the command line:

rake db:migrate

This completes all of the steps necessary to build your customer entity and all web pages for maintaining a list of customers. To test your applications you can now start the built test web server. To start the test web server, run the following command:

rails s

Now open your browser to the following URL: http://localhost:3000/customers. This web page contains a list of customers. In this case, the page should be empty and have a New Customer link available. Figure 5 shows the page. Click the New Customer link to open the New Customer web page as seen in Figure 6.

Figure 5: Customer listing page generated by the Rails scaffold generator.
Figure 5: Customer listing page generated by the Rails scaffold generator.
Figure 6: New customer screen generated by the Rails generator.
Figure 6: New customer screen generated by the Rails generator.

Changing the Home Page

If you happen to open the web browser without the customers suffix you will be greeted with a page like the one shown in Figure 7.

Figure 7: Default index.html page for Ruby on Rails.
Figure 7: Default index.html page for Ruby on Rails.

Ruby on Rails shows the index.html page found in the public folder by default. I am sure you agree this is not a proper page for your web applications. This next section explains how to create your own home page.

First, you can simply delete the index.html page.

Next, you will need to create a new controller and home page to display. Go to the command shell and execute the following command:

rails g controller home

This will create a new controller and corresponding set of files for maintaining entities around your home page. The next steps are to create a controller action and corresponding web page to display for your home page. Open the homecontroller.rb file that was generated in the app/controllers folder. Change the code to look like:

class HomeController < ApplicationController
  def index
  end
end

Now you need to add a view that corresponds to the name of your action. To create your view, create a new file called index.html.erb in the app/views/home folder. This file is an HTML file that will be processed through the Rails engine when it is accessed. Add a simple HTML header tag to this file.

Finally, you need to configure Rails to run the home/index controller action when the app is launched. To do this, open the routes.rb file in the config folder and add the following line:

root :to => "home#index"

This routing command tells Rails to run the index action in the home controller when the application launches. Now that you have changed out your root page, start the test web server using the rails s command and open your browser to http://localhost:3000.

Next, you’ll make one more minor change to the home page. Open your index.html.erb file and add a new line:

<%=link_to "Customers",customers_path%>

This will create a link to your Customers maintenance page. Figure 8 shows your home page with the Customers link created by the link_to helper.

Figure 8: Rails home page with a Customers link generated by the link_to helper.
Figure 8: Rails home page with a Customers link generated by the link_to helper.

It’s now time to take this application up a notch. In the next sections you will learn how to take advantage of the more interesting features of Ruby on Rails, namely data validations and relationships.

Adding Some Rules

Now that you have created your customer entity you will probably want to make sure that users are entering the data your application requires. Ruby on Rails comes with a number of built-in validation helpers that you can take advantage of out of the box. In this first example you will add a rule to require that users enter the name of the customer before it can be saved.

To add this rule, open the customer.rb file in the app/models folder and change your Customer class to look as follows:

class Customer < ActiveRecord::Base
  validates :name, 
:presence=>true, :uniqueness=>true
end

This rule will make sure that the user enters a value into the customer’s name field. It will also check to make sure the name is unique. After adding this code you can open your customer page. Try saving a customer without a name and you will receive an error like the one shown in Figure 9.

Figure 9: Customer screen with a rule violation.
Figure 9: Customer screen with a rule violation.

You can also validate values of an item against an array of values. Add these lines of code right above the validates :name line.

STATUSES=['Active','Inactive']
validates :customerstatus, 
    :inclusion =>{:in=>STATUSES}

This validation is going to make sure that the customer status field is in the list of values contained in the STATUSES array. Figure 10 shows you what happens when both rules have failed.

Figure 10: Customer screen with two rules violated.
Figure 10: Customer screen with two rules violated.

These are just two examples of the built-in rules provided by Ruby on Rails. There are also rules for validating that fields are in a specified range, in a regular expression, numeric and many others.

Your First Relationship

So far you have created a customer screen with two simple validation rules. Ruby on Rails also provides a nice set of features for linking different entities together. In this next example you will learn how to link the customer entity you already generated with a new entity you are going to generate using the same set of steps you used to create a customer entity. Run the following commands from your shell:

rails g scaffold customertype name:string
rake db:migrate

These two commands will build all of the data table and web pages for a maintaining customer types. You can access the customer types screens by typing http://localhost:3000/customertypes in your browser. Add three customer types now with the names of Gold, Silver and Platinum, respectively.

Once you have added your customer types you can go about the process of relating the two entities together. First let’s add the relationship from the point of view of the customer. In Rails terminology a Customer entity belongs to a customer type. To add this relationship you will add a line to your Customer model as follows:

belongs_to :customertypes

This relationship links customers to their respective customer type. Let’s take a minute and test this out. Add a customer with the following values “Test Corp”, “Active” and 1 in the name, customer status and customer type fields, respectively. Now shut down the test web server and run a new command:

rails c

This will open an interactive console for testing your Rails entities. Enter the following command into your command window. (Note: Case sensitivity matters.)

Customer.first.customertype.name

This command will do the following:

Now you need to add the reverse relationship. In this design, Customer types belong to many different customers. This relationship is established using the has_many operator. In the customer type model object, add the following line of code

has_many :customers

Now type the following code into the Rails console you activated using the rails c command.

reload!
Customertype.first.all

This code looks for the first customer type and lists all customers that have that entity attached to them.

Note: You need to be aware of the conventions that enable you to use these features with so few lines of code. When you created your customer entity, the customertype field was created with an id extension on it. Ruby on Rails is smart enough to figure out that the customertype_id field is linked to an entity called Customertype and will use its ID field for relating these entities together.

Changing Your View of the World

Now that your customer entity is linked to the customer type field you can alter your views to display data from these relationships. The first item to target is the list of customers. Instead of displaying the numeric value for a customer type, how about displaying the name of that entity? To do this, open the index.htm.erb file in the app/views/customers folder. Change the line that looks like:

<td><%= customer.customertype_id %></td>

to

<td><%= customer.customertype.name %></td>

This will display the name field from the customer type linked to the customer. Figure 11 shows the customer list with the customer types as a string instead of a numeric value.

Figure 11: This screen shows a list of customers with the name of the customer type displayed.
Figure 11: This screen shows a list of customers with the name of the customer type displayed.

Now let’s make one last change to this application. Instead of forcing the user to enter values for the customer type and customer status fields, how about providing a set of dropdowns for these two entry fields? To do this, open the app/models/customers/_form.html.erb file and change its contents to look like Listing 1:

Notice the use of the collection_select helpers. The first one will display all of the customer types from the Customertype table. The second will display all the values from the STATUSES array attached to the Customer entity. Figure 12 shows the customer screen with drop downs.

Figure 12: Customer screen with drop-down lists displayed.
Figure 12: Customer screen with drop-down lists displayed.

Deploying Your App

Now that you have created a rather simple Rails application, the next logical question is: How do I deploy this application? Well have no fear. Deploying a Rails application is rather simple these days. A number of vendors provide convenient and relatively inexpensive options for deploying your web applications. The two heavy hitters are Heroku and Engine Yard. Each of these vendors provides a solution whereby you can use Git to push different versions of your applications into the cloud.

It’s 2011 and the cloud is a logical place to run your applications from. I highly recommend checking out both of these services for deploying your applications.

Conclusion

As you can see, installing and constructing applications with Ruby on Rails is not that difficult. With tools like the RailsInstaller it has never been easier for Windows developers.

Listing 1: Customer data entry form with select boxes created using Rails form helpers

<%= form_for(@customer) do |f| %>
  <% if @customer.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@customer.errors.count, "error") %>h2>

      <ul>
      <% @customer.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :customertype_id %><br />
    <%= f.collection_select :customertype_id, Customertype.all, 
:id, :name %>
  </div>
  <div class="field">
    <%= f.label :customerstatus %><br />
    <%= f.collection_select :customerstatus, Customer::STATUSES,
 :to_s, :to_s %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>