Ruby On Rails For Java Developer

Ruby On Rails For Java Developer

In this blog I would discuss ruby on rails breifly from java developer perspective. Following are the contents of this blog:

What is Ruby on Rails?

Ruby on Rails is an open source Ruby framework for developing web-based, database-driven applications. One can develop web applications atleast ten times faster than any other typical java framework.
Rails’ primary goal was to bridge the gap between PHP and J2EE by providing an extensible, reusable web framework that offered an enjoyable, productive development experience. That goal was certainly met, and Rails became more than just a web framework.

How Ruby On Rails acheive rapid development with quality?

Rails takes full advantage of Ruby programming language.

Rails use two rails guiding principles:

  • Less software
    Rails require developer to write few lines of code to implement application.
  • Convention over configuration
    Ruby On Rails put an end to verbose long XML configuration files. There is no configurations files in Rails. Instead of configuration files, a Rails application uses a few simple programming conventions that allow it to figure out everything through reflection and discovery.

What is Ruby?

Ruby is a pure object-oriented programming language. Below we will compare it with java.

Ruby for Java developer


  • Memory is managed via a garbage collector.
  • Objects are strongly typed.
  • There are public, private, and protected methods.
  • There are embedded doc tools (Ruby’s is called RDoc). The docs generated by rdoc look very similar to those generated by javadoc.


  • You don’t need to compile your code. You just run it directly.
  • There are different GUI toolkits. Ruby users can try WxRuby, FXRuby, Ruby-GNOME2, or the bundled-in Ruby Tk for example.
  • You use the end keyword after defining things like classes, instead of having to put braces around blocks of code.
  • You have require instead of import.
  • All member variables are private. From the outside, you access everything via methods.
  • Parentheses in method calls are usually optional and often omitted.
  • Everything is an object.
  • Variable names are just labels. They don’t have a type associated with them.
  • There are no type declarations. You just assign to new variable names as-needed and they just “spring up” (i.e. a = [1,2,3] rather than int[] a = {1,2,3};).
  • It’s foo = “hi”) instead of foo = new Foo( “hi” ).
  • The constructor is always named “initialize” instead of the name of the class.
  • YAML tends to be favored over XML.
  • It’s nil instead of null.

Rails Architecture


Rails Application Structure

Following chart is above structure description:


Folder Name Description
app Holds application specific code. This includes models, views, controllers, APIs and helpers.
components Components are self-contained packages of controllers and views. These are normally utilized when there is a need to reuse a view that has associated reusable behavior.
config Configuration files for Rails environment, URL routes and database
db Database schema and migrations.
doc Holds application documentation generated from RDoc.
lib Application specific libraries.
log Development and production server logs.
public This folder is made available to the web server. It contains the dispatch scripts along with static content such as images, javascripts, stylesheets and default html files.
script Helper scripts for development server, automation, generation and plugin management.
test Unit, functional and integration tests along with test fixtures.
tmp Temporary directory for development server.
vendor Contains plugins and external libraries the application depends on.

Rails App folder Structure


Model, View and Controller


  • Rails interacts with models through the ActiveRecord component.
  • ActiveRecord models are based on the Active Record pattern defined in Martin Fowler’s “Patterns of Enterprise Application Architecture.”
  • Active Record defines a model structure that encapsulates a row in the database and domain logic on that data.
  • The ActiveRecord component requires only the database connection information to be configured in order to work.
  • There is no need for explicit object to database mapping. ActiveRecord elicits field information directly from the database itself at startup time.
  • It is possible to have a fully functional model that just extends from the ActiveRecord::Base class.

    class Post < ActiveRecord::Base


  • Currently, ActiveRecord supports the following 9 databases: DB2, Firebird,MySQL, OpenBase, Oracle, PostgreSQL, SQLServer, SQLite and Sybase.
  • Associations must be defined in the models themselves and those relationships follow specified naming schemes.


RHTML This is the default view for Rails applications. RHTML renders HTML based content back to a client web browser. RHTML also contains Ruby expressions that allow for programming within the view
RJS RJS templates are Ruby based javascript views. This type of view is used for asynchronous javascript calls (AJAX) made to a Rails app. RJS templates allow the view to execute javascript effects and manipulate the page where the AJAX call originated.
RXML RXML is Ruby generated XML code. It uses builder templates to easier construct an XML document to return to the client. Rails automatically returns RXML views as the XML content type.
  • All of the views in Rails are routed through a controller.
  • A controller action is responsible for passing information to a corresponding view. Any variables created in the instance of the Controller action will be made available to the view as well as application and controller specific helper functions.


    <% for post in @posts %>



    <% end %>


  • Controller take a dispatched request and decide what to do with it.
  • Controllers are responsible for interacting with the model, choosing which view to render and any redirects that take place.
  • The action is no longer a standalone class but simply a method within a controller.

    class PostsController < ActionController::Base

    def add

    def edit

    def delete


  • The default routing format to invoke one of these actions is: controller/action/id.

    class PostsController < ActionController::Base

    def show
              @post = Post.find(params[:id ])


  • By default Rails will render the corresponding view file with the same name as the action. Following is show.rhtml file

    <h1><%=@post.title %></h1>

    <p><%=@post.body %></p>

    posted by


Creating Simple Application

Step 1- Creating App

Step 2- Create Database

Step 3 – Provide database connection Entry in cookbook2/config/database.YAML

# MySQL (default setup). Versions 4.1 and 5.0 are recommended.
 # Install the MySQL driver:

# gem install mysql

# On MacOS X:

# gem install mysql — –include=/usr/local/lib

# On Windows:

# gem install mysql

# Choose the win32 build.

# Install MySQL and put its /bin directory on your path.


# And be sure to use new-style password hashing:



adapter: mysql
database: mydb
username: root
password: root
host: localhost

Step 4- Generate Application

For Recipe:

For Category :


Lets Look at generated Code

Model Code:

class Category < ActiveRecord::Base


Controller Code:

class CategoryController < ApplicationController

def show
        @category = Category.find(params[:id])

def new
        @category =

def create

@category =[:category])


flash[:notice] = ‘Category was successfully created.’

redirect_to :action => ‘list’


render :action => ‘new’




View Code:

<h1>Editing category</h1>

<% form_tag :action => ‘update’, :id => @category do


<%= render :partial => ‘form’ %>

<%= submit_tag ‘Edit’ %>

<% end %>

<%= link_to ‘Show’, :action => ‘show’, :id =>

@category %> |

<%= link_to ‘Back’, :action => ‘list’ %> 

Step 5- Run development server

Here you go



Leave a Reply

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

You are commenting using your 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