Monday, October 10, 2011

A glimpse of Active Record



What is Active Record ....

Active Record controls the interaction between your application and the database. The main advantage of Active Rec
ord is, it reduces your configuration.Also Active Record's meta-programming dynamically adds capabilities to your classes based on the contents and structure of database. Finally it reduces the coding effort from the developer.


How Active Record works ...

With any Active Record implementation , users manipulate database tables through record objects. Each Active record object has CRUD (Create, Read, Update, Delete) methods for database access. This kind of mechanism allows a simple design and direct mapping between database and the application.

Most of the frameworks follow the strategy called ORM (Object Relational Mapping). In this technique, database tables and objects are created independently. Then a mapping created between objects and database tables using some code. The drawback for this mapping technique is , you need to specify each colun in database, in object models and in configuration file (sometime).

Instead of using mapping technique , Active Record uses wrapping technique. After building the relational database, user wraps each table with Active Record class. Each instance of the Active Record class represents a row of the table. Even a new column added to the table, the framework automatically detects it and adds to the active record class.

While using ActiveRecord, we need to be careful about the naming convention.Rails uses several naming conventions.

Class and table names : Class name should be singular where as table name should be plural. Also while defining a class, we should use the camel case while naming the class. For example if table name is 'users' , then class name should be 'User'.

Identifier : ActiveRecord automatically finds a column called 'id' and uses it as a unique identifier.The 'id' should be integer type and value should be populated by the database .Staying with these convention saves you some configuration and also makes your code much easier to understand.

Foreign keys : Foreign key should be named as _id.

Lets check with an example ....

class Product < ActiveRecord::Base

end

In the above example , I have defined a class called Product, which inherits the property of the Base class in the ActiveRecord module. From the naming convention we can know that the above class wraps the database table called products . The above information is enough for the Base class to query for all the columns in the products table.

Now check another example ....

class Product < ActiveRecord::Base

belongs_to :category

end

The above definition is very similar to the previous one. But here the line “belongs_to :category” specifies that there are many-to-one relationship between Product and Category (here Category wraps the table categories). The term 'belongs_to' is a method inside 'Base'. Similarly there are lots of method available which help us minimizing the code.

Now let's see how Active Record helps in minimizing the query.

# Find the client with primary key (id) 10.

product = Product.find(10)

Its SQL equivalent is :

SELECT * FROM products WHERE(products.id = 10)

Similarly..

# Find the client with primary key (id) 10.

product = Product.first

Its SQL equivalent is :

SELECT * FROM products LIMIT 1

Like this you can find lots of methods which really reduces the coding pain.

To know more about Active Record and its methods, you can check the following sites.

http://guides.rubyonrails.org/active_record_querying.html

http://api.rubyonrails.org/classes/ActiveRecord/Base.html

Thursday, September 8, 2011

Setting up RoR and Getting Started With RoR.

I am sure you must be curious to start your first application in RoR and don't know how to install rails on linux. Just kidding :)

Here I have explained few steps to setup the rails on Ubuntu.

As you know RoR can be installed on windows,linux and mac. But personally I prefer to work on linux. Here I am mentioning steps for installing rails on linux (Ubuntu 10.04 box).

We are going to use 'aptitude' command to install the packages. 'aptitude' is a known command in linux to install packages. If you don't have 'aptitude' installed on your system, you can install it using the following line.

$ sudo apt-get install aptitude

Now 'aptitude' is installed and we need to make sure that we have the latest sources on our box and we don’t run into any package-related issues, such as not being able to install some packages. So now we run the below command.

$ sudo aptitude update

Next, we are going to install git , curl and build-essential which are required to install and use RVM, and compile Ruby versions. For your information git is a version control system and both git and curl is required to install RVM .To install these three packages we'll use the following command.

$ sudo apt-get install build-essential git-core curl

At this point you must be having question regarding RVM. What is RVM and why we use this ?

RVM (Ruby Version Manager ) is a command-line tool which allows you to easily install, manage and work with multiple ruby environments . Lets take one example, sometime you required to work on different projects on different ruby environment such as one on Ruby 1.8.2 and another one is on Ruby 1.9.2 . So in this case it is very important to manage the different version on the single system. This situation can be handled by RVM.

Now let's install RVM on our system using the following command.

$ bash < <(curl -s https://rvm.beginrescueend.com/install/rvm)

Once the command is executed, we need to add a line to ~/.bashrc file which will load RVM .The above file responsible for setting up our bash session.

$ echo '[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"' >> ~/.bashrc


Now we are set with RVM. Next we need to know what other packages we need to install for Ruby. Now RVM will tell us, what are the required packages. Use the following command.

$ rvm notes

When we run this command it'll output a set of notes on the terminal window. Find the below note among the set of notes.

# For Ruby (MRI & ree) you should install the following OS dependencies:
ruby: aptitude install build-essential bison openssl libreadline6 libreadline6-devcurl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf

Now copy the command (which is mentioned after 'ruby:' )and execute it to install other packages.


$ sudo aptitude install build-essential bison openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf


Please note that the above command should be in online. Otherwise it may miss some package installation.Now we are ready to install any version of ruby and set default environment.

Execute the below command to install a particular version of ruby.

$ rvm install 1.9.2

This will install the ruby1.9.2

To use the same we can use the command

$ rvm use 1.9.2

But for setting the default environment, we can use the following command.

$ rvm -–default use 1.9.2

Now you can check what is the ruby version you are using for application using the below command

$ ruby -v

At this point we are set with RVM and ruby. Now we need to install rails and go for our first application.

$ gem install rails

This will install rails and its dependencies including bundler .
We are all set with our environment. Let's move towards our first application.

Here I am creating a directory to keep all my rails applications. And then creating my first application within it.

$ mkdir rails_apps

$ cd rails_apps

$ rails new my_first_app

While execute the last command “rails new my_first_app”, you can see it'll create some files and folders. These are the standard files and directories of the application.

Now if you open the “Gemfile“ which resides inside “my_first_app” directory, you can see couple of lines (some of them are commented). Here we can include our required gems for our application. To include any gem we need to write a simple statement.

gem 'gem-name'

After including the required gems we can run the bundle install to install all gems for the application. In our case we don't need any additional gems as it is our first application.

Now run the below command.

$ cd my_first_app

$ bundle install

This will take few time to install all the default gems and additional gems for the application. After completion of above command execute the below code to start the server.

$ rails server

This will start the local web-server. In our case WEBRick is the default web-server which comes along with rails package.

Now we are ready to open our first application on the browser. Just type http://localhost:3000 on your browser and you can see the default rails page. 3000 is the default port used by the web-server. Remember it is one default rails page , we can add controllers,models and views to our first application to create our own application. Here I am not discussing the MVC (Model,View and Controller). Once we get the default rails page , we are assured that rails and application setup is OK and we can go ahead for more coding.

I hope the above information will help you to set-up your first application in RoR. For further assistance feel free to send your query to me (asisht@mindfiresolutions.com) or post your query in the comment section, I'll be happy to assist you solving your problem.



Friday, September 2, 2011

Why Ruby-on-Rails ?

As a web developer you can raise few questions before choosing any new technology. Why should I go for RoR (Ruby On Rails) ? The first and most important reason is it is open source. It costs nothing to download and use. Is this enough for switching to RoR ? No there are other reasons. RoR has a compact design. It follows the MVC structure , which allows the developer to separate the business logic,design and control structure. The most interesting thing about RoR is , you can find a large community for the framework. There are hundreds of open-source contributors . You can find thousands of gems and plug-ins to integrate with your application. As a result your development becomes much faster in comparison to other scripting languages. Beside the gems and plugins, the scaffolding mechanism of rails , makes the development much faster. You only need to execute few commands on the command line and it will generate the code for you.

Seems interesting. PHP is open-source having a great community. Then what is the difference between PHP and RoR ?

There are couple of differences between PHP and ROR although both are open-source used widely.

  • Firstly we need to understand that PHP is a scripting language where as RoR is a framework based on Ruby. As I had mentioned earlier RoR uses MVC structure where as for PHP you need to explicitly design the architecture to follow MVC structure.
  • Also ROR is much more object oriented than PHP.
  • Again RoR includes a web-server while developing (the default web-server is WEBrick ) though you can use different web-servers like Mongrel , Apache, nginx , lighttpd , etc . But for PHP you need to install the web-server separately.
  • In comparison to PHP, RoR is remarkable for its use of javascript libraries for Ajax.
  • RoR coding is very simple because of its easy syntax and simple implementation since the framework is based on Ruby and it inherits the property of Ruby.
  • RoR is a rapid application development tool. Developing a website using PHP is fast and it is easy to learn PHP. But a new PHP developer can't develop an application in PHP in faster and secure manner. But in case of Ror a new RoR developer can do the same . This is because of RoR structure, coding style and features .

In real sense RoR is a truly rapid application development tool.