Over a million developers have joined DZone.

HABTM Relationship MySQL Tables For Use In Rails

·
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`)
)


Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}