DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

HABTM Relationship MySQL Tables For Use In Rails

12.19.2006
| 5259 views |
  • submit to reddit
        This is an example of the tables I create when I want to have an HABTM relationship between 2 tables:
   Table 1: products
   Table 2: tags

DROP TABLE IF EXISTS `products_tags`;
DROP TABLE IF EXISTS `tags`;
DROP TABLE IF EXISTS `products`;

CREATE TABLE `products` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(100) NOT NULL,
  `price` decimal(10,2) NOT NULL,
  PRIMARY KEY  (`id`)
)

CREATE TABLE `tags` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(64) NOT NULL,
  PRIMARY KEY  (`id`)
)

CREATE TABLE `products_tags` (
  `product_id` int(11) NOT NULL default '0',
  `tag_id` int(11) NOT NULL default '0',
  PRIMARY KEY  (`product_id`,`tag_id`)
)