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?
views:
103answers:
3This 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.
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.