monk
monk

Reputation: 4825

Product, Category and Brand database relation in Rails

I am creating a website using Rails and I am using MySQL for Database. There are some products, it has categories like Smartphones, Tablets, Digital Watches and then there are Brands like Apple, Samsung and HTC. How do i Make relationship between them in Rails, I mean in a conceptual way.

A category has many products and a product might have many categories. And then there are Brands a product has one Brand and Brand has many products. How do I approach this and in what way should I develop it?

Any kind of help whether conceptual or technical (in terms of code) would be great.

Upvotes: 0

Views: 2516

Answers (1)

catalinetu
catalinetu

Reputation: 660

here is a structure that you can use:

CREATE TABLE `category` (
  `id` int(11) NOT NULL,
  `category_name` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

CREATE TABLE `brand` (
  `id` int(11) NOT NULL,
  `brand_name` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

CREATE TABLE `product` (
  `id` int(11) NOT NULL,
  `product_name` varchar(100) DEFAULT NULL,
  `product_specification` varchar(255) DEFAULT NULL,
  `id_brand` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `id_brand` (`id_brand`),
  CONSTRAINT `product_ibfk_1` FOREIGN KEY (`id_brand`) REFERENCES `brand` (`id`)
) ENGINE=InnoDB;

CREATE TABLE `protuct_category` (
  `id_product` int(11) DEFAULT NULL,
  `id_category` int(11) DEFAULT NULL,
  KEY `id_product` (`id_product`),
  KEY `id_category` (`id_category`),
  CONSTRAINT `protuct_category_ibfk_1` FOREIGN KEY (`id_product`) REFERENCES `product` (`id`),
  CONSTRAINT `protuct_category_ibfk_2` FOREIGN KEY (`id_category`) REFERENCES `category` (`id`)
) ENGINE=InnoDB;

Upvotes: 1

Related Questions