Saturday, May 10, 2008

Rails 2.0: Why change the scaffolding

Rails 2.0.3 is now in market. There are many changes such as multi-views, using Model objects as resource handlers etc. However, the main change is how the scaffolding is done. Gone are the days of issuing Scaffold command and the table to be scaffolded. For example, if the name of table to be scaffold is Emp having Id and name . In the pre 2.0 era I would have given the following command

ruby script/generate scaffold Emp empAdmin

That would have generated the model named Emp with controller having the name empAdminController and the related views. Now how things have changed in 2.0

ruby script/generate scaffold Emp name:string

Yes, I had to pass the non id attributes to the scaffold command. Now if it is a trivial table with 3 or 4 columns then well and good. However, a table in real world will have atleast 15 columns then its just too much. I know scaffold is not seen as a good parctice in 2.0. However, scaffold was the reason I admired Rails. Now it seems like Rails is also making development a bit complex. Apart from that Rails 2.0 is really great.

Saturday, May 3, 2008

Active Records v/s Hibernate - Round II

Welcome to the round two of Active Record v/s Rails. This round is based upon implementation of ORM classes. Lets start with Hibernate. The steps to implement ORM class in Hibernate are:

  1. Name the class (preferable) according to the table. For example, if table is named Employee, then the class is also named Employee. This is preferable but optional.
  2. Next declare the instance variable corresponding to the attributes of the table with which class is to be mapped. For example, if the Employee table has an attribute named Name, then the class will have an instance variable named Name. Its data-type will be the Java equivalent of SQL type. If Name attribute is varchar, the name instance variable will be String.
  3. Last step is to implement getters and setters for the instance variables.

Next let us see how to do this with Active Record
  1. Name the class according to the table. For example, if table is named Employee, then the class is also named Employee. This is mandatory if you do not want to override the defaults.
  2. Derive the class from Base class of ActiveRecord package. For example, the Employee class needs to be derived from Base::ActiveRecord.
Thats it just two steps. No need to declare any instance variable or any getter/setter. So how does Rails gives you the data? It does it as follows:
  1. When the ORM object is created Rails reads the schema of the table and through meta-programming, creates corresponding instance variables in the ORM object.
  2. Next, Rails populates the object with the data from the table.
Using meta-programming and reflection Rails dynamically does everything. In the next post the third round will start on the basis of Query Language supported by both.