Sep 23, 2009

Rails from a VB/SQL Perspective

If you're a database programmer like me and my colleagues, you may need to think a little different now.

Instead of tables, queries and triggers - forget about those. Now we are able to develop database independent software (provided you don't mess up with hardcoded SQLs).

To start with, first we have the Schema (which are the table structures). In Rails, the database design is encapsulated in the Model and Migrations. This are the 2 things you need to focus on.

Our logics on database can be taken care by ActiveRecord. Association (such as 1-to-many, many-to-many relationships) and data validations (such as required fields, FK fields with referential integrity) can be easily defined in the Models.

And best part, only 1 or 2 lines of codes will take care of the rest. This is a high-level DB programming compared to coding individual lines to read from different tables and validate on the data entered.

For example:

In User class
has_many :links
has_and_belongs_to_many :groups (this is my favorite, many-to-many)
validates_presence_of :name
validates_uniqueness_of :login, :email
validates_length_of :login

In Group class
has_and_belongs_to_many :users

My first confusion starts with the schema. How do I start? Model first or database first. Now, that I've cleared the confusion, we can forget about database. You can use scaffolding or generate a model instead by calling:

script/generate scaffold ModelName name:string notes:text
or
script/generate model ModelName name:string notes:text

The name:string notes:text is an example. You can ignore that as it is optional. Once done, you can go to db/migrate folder to edit the migration file created automatically for you.

Once you are happy with your migration files, you can then apply the changes to database by running rake db:migrate

You can repeat this for all the Models (or tables) you want to create.

It will also auto-generate a file called db/schema.rb, which will collectively add all the incremental changes / additions of your models.

For creating new database with the table structure, you can either apply the migrations with the rake db:migrate command or by using the schema file, which is rake db:schema:load that will speed up the process.

What are Callbacks?

In VB, it is called an event. Windows development are mainly event-driven programming. And callbacks are similar. In ActiveRecord, we can define callbacks :before_add, :before_remove, :after_add and :after_remove.

There's plenty more and you can refer to the AR documentation in http://api.rubyonrails.org or directly here: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

No comments:

Post a Comment