Saturday, March 1

has_and_belongs_to_many : habtm in Rails

has_and_belongs_to_many, simply "habtm" of rails would address/handle the many to many relationships of the tables.

Let us take this scenario where we have two tables, "products" belong to "categories" and "categories" belongs to "products" in more than one ways. That is each product belongs to many categories and each category contains many products. In each of the model, category and product the relation would be shown using habtm (has_and_belongs_to_many).

Closely observing the above example, we can see that the products table and categories table contains habtm relation. There is an intermediate table "categories_products", which would carry the primary key of each table.

At the database level this is achieved using an intermediate join table. The convention followed here is the name of the join table is the concatenation of the two target table names but in alphabetical order. In our example, we joined the table categories to the table products, so Active Record will look for a join table named categories_products.


  1. The join table carry the foreign keys of each table.
  2. There will be no model for this intermediate table (categories_products)

Well that precisely explains how we implement many to many relationships in Rails. That is not all there is one more way of expressing the relationship between tables, "has_through" which we will touchbase later.

1 comment:

Karthik Blog said...


when i created i cant see categories_products table in my mysql what can i do