Showing posts with label models. Show all posts
Showing posts with label models. Show all posts

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...