Wednesday, April 25, 2012

Database design advice in Rails, The Pizza, Topping and Order

Yes, its another database question with the pizza analogy.
The ones I've seen don't seem to click just right, so here goes.



I need to be able to order multiple pizzas with any number of toppings in a single order.
Its a basic shopping cart pattern, but the toppings are making it difficult to implement.



The base models are,



class Pizza < ActiveRecord::Base
has_and_belongs_to_many :orders
has_and_belongs_to_many :toppings
end

class Topping < ActiveRecord::Base
has_and_belongs_to_many :pizzas
end


Pizza and Topping tables serve as the holder for the information of pizza and topping types that can be ordered.



class OrdersPizzas < ActiveRecord::Base
belongs_to :order
belongs_to :pizza
end

class PizzasToppings < ActiveRecord::Base
belongs_to :topping
belongs_to :pizza
end

class Order < ActiveRecord::Base
has_and_belongs_to_many :pizzas
end


[Added]



Some clarification, the database design is intended for a shopping app, so being able to setup a "menu" by an admin, and users being able to see the menu, and order from it is imperative.



The operation of this goes in two steps, first you need to make a menu by creating the Pizzas and toppings, and associating them, not all pizzas can have all the toppings.




A Cheese Pizza can have extra olives, and extra cheese as toppings



A Peperoni Pizza can have only extra cheese for toppings




Step two is actually placing the orders according to the entered data, thus all the many to manys.



Now the question is, after entering the data above, I want to place an order




Peperoni Pizza with extra cheese



Cheeze Pizza with extra olives




in a single order, how should it be designed?



All I can think of is to add a



class OrdersPizzasToppings < ActiveRecord::Base
belongs_to :orders_pizzas
belongs_to :topping
end


so I can distinguish which pizza has the toppings, but that does not look like the right way to go.





No comments:

Post a Comment