Question

Can anyone explain to me how the (HABTM or many to many) "has and belongs to many" principle works? Say I have a users table and books table and then I have a table users_books where the IDs are. When would I need to actually use this principle and how would it work?

Was it helpful?

Solution

Are you asking why you need many-to-many relationships (which is what HABTM is)?

In the case you mention above a user may own many books - how you you represent that in a database Lets say you have two tables, books and users, in the users table you can't add one column per book for each book the user may own as you don't know what the upper limit on the number of owned books is. You could add a column called 'books' and store a 'collection' of books in this column (maybe as XML or comma separated) but this makes lots of database queries hard (such as identifying individual books that user owns).

The same is true of the books table, how many users own a particular book? again you can't know up front so you can't add multiple 'user' columns to the books table and adding a single 'users' column with a collection of users doesn't help.

The solution to this problem is to add a 'join' table, usersbooks say, that contains two columns, a userid and a bookid. This table links the users to the books. So if I have two users with ids 1 and 2 and three books with id 101, 102 and 103 the join table may look like:

userid  bookid
1       101
2       101
2       103

This is where the users_books comes in in HABTM - it's the join table between users and books.

OTHER TIPS

Has And Belongs To Many handles the many to many relationship between tables in a database. In your case, it would handle the relationship between users and books, as one user can have many books, and one book can have many users.

alt text

This blog post looks like a pretty good explanation and illustration of the concept:

has_and_belongs_to_many : habtm in Rails
http://sumanthtechsavvy.blogspot.com/2008/03/hasandbelongstomany-habtm-in-rails.html

This section of the Rails Associations guide has some good information on the way this works in Rails. You should also consider the possibility of a through association in the event that you need to store more information about the association itself. Wikipedia has a brief article on the basic concept of many-to-many data models that may also prove instructive.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top