Ancinek Ancinek - 1 month ago 10
MySQL Question

Rails and MySQL - structure Product with sizes and prices

What is the proper way to structure models and migrations in Rails so I can have relationships like this:


I think the image is clear enough but:

  1. One product can have different sizes

  2. A size can have different prices dependent on the product it is associated with.

I am in a school project and the only guy who has ever done something with code, and we need to structure something similar to this (it's biological but the idea is the same).

Would generating:

For product:

rails generate model Product name:string

class Product < ApplicationRecord
has_many :sizes
has_many :prices

For size:

rails generate model Size size:string product:references

class Size < ApplicationRecord
has_many :products
has_many :prices

For price:

rails generate model Price price:decimal size:references product:references

class Price < ApplicationRecord
has_many :sizes
has_many :products

solve my problem?

I am in the middle of reading this but it is not helping.

dkp dkp

Can it be like this-

Product model:

has_many :sizes
has_many :prices, through: :sizes

Size model:

 has_many :prices
 belongs_to :product

Price model:

belongs_to :size