Wednesday, February 13

Relationships between tables - How ActiveRecord handles?

Keywords:
  • has_one,
  • belongs_to,
  • has_many,
  • has_and_belongs_to_many
  • polyphormic
  • one-to-one
  • one-to-many
  • many-to-many
It's known that any web application will contain bunch of tables and they are dependent on each other. With normalization as the key, we avoid redundancy and have more relationships with tables using keys. In database terms, the following are the relations allowed/known between tables -> one-to-one, one-to-many, many-to-many. Let us digg more, how ActiveRecord handles these.
ActiveRecord supports the above mentioned relations and in fact, comes with set of key words which are easy to use, understand and pretty clean.
Let me take few snapshots from David's book:
Note:
  1. invoices is the table name
  2. orders is the table name
In the above snaphot, the motive is to declare the relationship between the orders and invoices tables. It's clear that orders will have invoices, i.e., invoices belong to orders. And watch out we will be using same words. Now to have the relationship declared, we will go to their models (Remember: the application access the tables through model so it makes sense to declare relationships also in models).

Now I am into order model, orders having invoices. so the key word that we use here is has_one and then followed by the model name (Note: It is not table name, this is not plural).
has_one :invoice

Next will go to invoice model, since invoices belongs to orders we use the key word belongs_to and then followed by the model name.
belongs_to :order

Well there is not xml written for models, no xml written for relationships. But simple convention and defined keywords done the job for us.
And as you might have guessed the has_many comes into use when the orders table is having relationship with one more table (say, line_items). The below snapshot will help you to understand the syntax and it's usage.

Will look into other keywords and other relationship in the following posts...

1 comment:

Uday Bhaskar said...

Hi,

Can you help me solving this problem... and it is

User has many Projects, Project has many users, and user has multiple roles for a Project.

Eg:

Ram, John are multi skilled persons.

Ram and John are associated with many Projects in a company

Project A has many Users (Ram, Shyam, John, Ryan)

In Project A, Ram takes the roles as 'Configuration Manager and Network Manager' and John takes the roles as 'Developer and System Administer'.

In Project B, Ram takes roles of 'Developer and System Administer' and Ryan takes roles as 'Configuration Manager and Network Manager'.

In Project C, all users are developers.

So we have three tables User, Project and Role

Users are Ram, Shyam, John and Ryan
Projects are Project A, Project B and Project C
Roles are Developer, System Administrator, Configuration manager and Network Manager.

How do we design this?

Thanks,
Uday.