IntroductionToRubyOnRails

Contributed by John Kostaras
December 2007

The new Netbeans 6.0 IDE contains full support for Ruby and Ruby on Rails. Ruby on Rails is an exciting new framework that allows for rapid web development based on the powerful Ruby scripting language.

In this article I demonstrate how you can develop in Netbeans 6.0 the example found in the book Rails for Java Developers (see the References). You will also need to download and install MySQL 5. Ruby on Rails applications are normally combined with a database. You may also wish to install the MySQL Tools, like the MySQL Administrator and Workbench. Alternatively, you may wish to install xampp for Windows or lampp for Linux which comes with a web admin interface. If your MySQL installation is finished, then let's begin.

With Rails you can build a simple web application nearly instantly, using the scaffold code generator. This tutorial will walk you through creating a functioning web app in about fifteen minutes. You’ll create a simple, form-based CRUD application for creating, reading, updating, and deleting people. I won’t explain the steps in detail here, even though most of them are straightforward. The interested reader may refer to the book Rails for Java Developers which explains each aspect of the following code example in more detail.

As Netbeans 6.0 comes already with support for Ruby and Rails, there is nothing else to do, than, off course, start the IDE. Click on the New Project button and select the Category Ruby and Project Ruby on Rails Application as shown in the following figure:

Fig.1

Click on Next. We shall create a Rails application named people. Edit the project name in the next screen as shown in the figure below:

Fig.2

If you want to use Native Ruby with your Rails application, configure that first (in the Options --> Preferences dialog) or click on Change button in the above dialog box and select Native Ruby. Click on Finish. Netbeans has created a number of folders under people folder. This is a Rails project. Rails applications use the Model-View-Controller or MVC design pattern. In short, this design pattern decouples the presentation layer or web pages (View) from the business logic or database layer (Model) and bridges the two via Controller. You have probably already spotted that folders named Models, Views and Controllers have already been created by the Rails application. Additionally, a Helpers folder has been created as well as various folders for testing and logging, everything a modern developer needs. Agile development straight away.

Next step is to create our database, or databases. Rails use 3 databases, one for testing, one for development and one for production. Following the book, you will create two databases, people_development and people_test. You can use MySQL Administrator to create these databases or the phpmyadmin if you are using xampp or lampp. If you wish to store data in other language than english, then you would better use one of these collations: utf8_unicode_ci or utf8_general_ci. If you don't want to use any of the above tools, then simply open a dos or shell window and type the following:

> mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.0.45-community-nt MySQL Community Edition (GPL)

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> create database people_development;
Query OK, 1 row affected (0.30 sec)
mysql> create database people_test;
Query OK, 1 row affected (0.30 sec)
mysql> exit
Bye

The above instructions assume MySQL, with no password on the root account. Of course, this is a serious security risk but this is the default assumed by Rails. If you are a prudent guy and don't leave empty passwords, especially for root accounts, then edit people --> Configuration --> database.yml file adding the password of the root account for your database.

Next step is to create an ActiveRecord model object. Right click on the Model folder and select Generate. You will create a model (class) Person. Type Person in the Arguments texbox and click on OK. Usage information for each generator is displayed right there in the dialog. You can also directly install additional code generators by clicking on the Install Generators button.

Fig.3

Rails is working:

      exists  app/models/
      exists  test/unit/
      exists  test/fixtures/
      create  app/models/person.rb
      create  test/unit/person_test.rb
      create  test/fixtures/people.yml
      create  db/migrate
      create  db/migrate/001_create_people.rb


Notice how the model file is named person but the fixture file (which may contain more than one person) is named people. Rails works hard to sound like the way people talk and automatically uses the singular or plural form of words where appropriate.

class Person < ActiveRecord::Base
end


Edit the db/migrate/001_create_people.rb file so the setup section looks like this:

def self.up
   create_table :people do |t|
     t.column :first_name, :string
     t.column :last_name, :string
     t.column :age, :integer
   end
end


Update the database by running the rake db:migrate task. Rake is an automation tool similar to Java’s Ant. Right click on People and select Run Rake Task --> db --> Migrate.

Now check your people_development database with either MySQL Workbench or phpmyadmin. You should see a table people with 3 fields, first_name, last_name and age.

And here comes the last step, to generate a scaffold. Right click on the people project and select Generate. Select scaffold from the combo box and add Person to Model Name. Click OK. No need to add a Controller name. Rails does a good work and will provide people as the controller name for you!

Fig.4

That's it. Run you application. WEBrick, the builtin Ruby web server, is automatically started on project creation (as well as on Run, if not already running). There is a WEBrick console window which shows the output of the web server, like the requests it has processed.

There is no deployment step - the application is already deployed in place. Enter this URL to your favorite brower http://localhost:3000/people and voilà, you have a full web application with very few steps. You should see a simple, form-based application for creating, reading, updating, and deleting people.

Try it for a few minutes, and make sure everything is working. The scaffold isn’t pretty, but it provides a lot of functionality for little work. If you review the steps you just went through, there were only three lines of code, and those were to create the model object. If you already had a database schema, those three lines would go away, and you would have a web application up and running with zero lines of handwritten code.

Fig.5

Let's run the automated tests for your application. Right click on people and select Run Rake Task --> tests --> units. Even if we didn't write any tests, when you executed scaffold, Rails created some for you. Rails helps you test your project by putting testing in place on day one. Rails is primarily about generating code.

In Rails, the development cycle is carefully designed to minimize interruption. You change your code and refresh your browser to see the changes. That’s all. There is no compile, deploy, or server bounce necessary. This has two advantages: faster development and you learn as you go.

Extending our basic web application


Let's add some data validation to our People application. If you create a person with an empty first name and last name, it will happily store a bogus record in the database. Validation is critical to web applications, and Rails makes validation simple. To add validation, edit the file people/Models/person.rb like so:

class Person < ActiveRecord::Base
  validates_presence_of :first_name, :last_name
end


The validates_presence_of part requires that both the first name and the last name be present, i.e. not be nil. Navigate your browser to http://localhost:3000/people/new, and try to create a person with no name. When you click on Create, you will see an error message on the following page.

Fig.6

When you add validations to a model, their effects automatically propagate to the view, with no additional work necessary.

Finally, let's add a search box in the list view. Edit file people/Views/layouts/list.rhtml and insert the following code right after

Listing people

:


<%= start_form_tag('', :method=>'get') %>
  People named:
  <%= text_field_tag 'search', @search %>
  <%= submit_tag 'Find'%>
<%= end_form_tag %>


This only causes a search box to appear in the list view. Open file people/Controllers/people_controller.rb and find the list method:

def list
  @person_pages, @people = paginate :people, :per_page => 10
end


If the user specifies no search term, the method should continue to work as is. If there is a search term, we will compare against both first and last names. Replace it with this expanded version (from Rails for Java Developers book):

def list
  @search = params[:search]
  if @search.blank?
     @person_pages, @people = paginate :people, :per_page => 10
  else
     query = [first_name=:searchOrLast_name=:search,{:search=>@search}]
     @person_pages, @people = paginate :people, :per_page => 10, :conditions=>query
  end
end



Fig.7

Now, run your application, refresh your view of http://localhost:3000/people/list, and add a few people if you haven’t already. Then try some search terms. The list is updated to show only the matching names.

As is so often the case with Rails, we didn’t have to do anything to test our changes, other than refresh the browser. Our changes themselves were minimal and to the point. We didn’t have to tell Rails how to convert URLs into controller methods, how to connect models to views, or how to find the right view for a controller action. Almost everything in Rails has a default, and you need configuration only when you want to override the defaults.

That's it. This was the sample application from the book Rails for Java Developers, implemented using Netbeans 6.0. As you saw, Netbeans 6.0 provides a very good support for Rails and makes Rails development even easier.


References

  1. Halloway S. & Gehtland J. (2007), Rails for Java Developers, The Pragmatic Programmers.
  2. RubyOnRails
  3. Strobl, R. NetBeans: Ruby Developer's New Best Friend, Part 1, InfoQ, http://www.infoq.com/articles/netbeans-rubyide1
  4. Strobl, R. NetBeans: Ruby Developer's New Best Friend, Part 2, InfoQ, http://www.infoq.com/articles/netbeans-rubyide2
Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo