Reputation: 173
I need to code a model relationship in Ruby on Rails consisting of 4 levels:
Clothing Shops -> Brands -> Clothing Brands -> Shirts
If you wanted to do this the most efficient way, would you program something like this pseudocode?
shop< has_many :brands
attributes: name,url,etc
brand< belongs_to :shop
has_many :lines
attributes: name,owner,etc
line< belongs_to :brand
has_many :shirts
attributes: name,year,etc
shirt< belongs_to :line
attributes :name, price, color, etc...
Or something like this:
shirt<
attributes : shop, shopName, shopUrl, brand, brandName, line, name, price, color, etc...
I mean, is it better to have more models with less attributes or less models with more attributes?
Upvotes: 1
Views: 377
Reputation: 9002
Organizing data into multiple models and relationships between is optimized for storage as it reduces data redundancy.
The other approach, i.e. having only a Shirt model with shop, brand and line data as its attributes is definitely not optimal from storage perspective, but it much more search-friendly.
So it really depends on the use case.
Often mixing both approaches is the best choice. You can use relational database as your primary source and keep the data there in normalized form (multiple models, relationships). But also have another data store (which you periodically populate from primary source) which is optimized for search (e.g. Elasticsearch index).
Upvotes: 1
Reputation: 5085
In my experience is always easy to look up for the objects, for instance shop and shirt makes lots of sense as objects, but the tricky ones are brand and line, there you need to think if it would make your life easy having them as objects or attributes, for example if you are gonna be doing lots of things with the brand, like searches, filters or special views, there will make sense to have them as separated objects, or if you are gonna have lots of products of the same brand maybe is really important to be sure that the names doesn't repeat in different syntax eg: "Dior" and "dior", on the other hand maybe you are dealing with just 10 products from different brands and the name is not really an issue.
Now the line is the same thing, how important is it, and would be better for your features to have it as a new object.
I'm personally, 80% of the cases i go with a new model, because I'm usually dealing with large databases and it would be easier to read the code and the features implemented in that way.
Upvotes: 2