Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

HABTM Relationship MySQL Tables For Use In Rails

DZone's Guide to

HABTM Relationship MySQL Tables For Use In Rails

·
Free Resource
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:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}