Model with extra columns based on belongs_to model
I am building a products database. Each product belongs to a category. There can only be products under sub-sub-categories. Each Product have attributes like name, ean_number, price, width, height, depth, weight etc. But then there are some custom attributes based on the category! Like energy_class, number_of_programs, sound_volume, etc! I am talking about something like this:
Category
|
|--Category <- This Category have extra information about extra attributes for Products
| |
| |--Category
| |
| |--Product
| |
| |--Product
|
|--Category <- This Category have extra information 开发者_Python百科about extra attributes for Products
|
|--Category
| |
| |--Product
| |
| |--Product
|
|--Category
|
|--Product
|
|--Product
I am not sure how to build it up. I need a database for categories and products. But then a category need to know what extra attributes to add to the product. So maybe I have to make a table for extra_attributes? And then make a has_many association between category and extra_attributes? But then a product need to know about this association too! Maybe I am thinking in a completely wrong direction...! Maybe I should make different Product types? I hope you can guide me!!
Perhaps you can use single table inheritance to get what you want. Rather than have a separate class for categories, create the tree of product types using subclasses. These subclasses can define validations for the extra attributes that they allow.
For example:
Product
NamedProduct < Product (defines validations on :name)
ByWeightNamedProduct < NamedProduct
ColorProduct < Product (defines validations on :color)
CoolColorProduct < ColorProduct
精彩评论