Hello, everyone
Ok, I admit the title isn't really clear, so come a use case.
We have a Store, which has Products; each products is in a Category. Because I need to retrieve Product quickly, I've ended up with this kind of structure:
Ruby:
class Store
include Mongoid::Document
field :name
embeds_many :products
embeds_many :categories
end
class Category
include Mongoid::Document
field :name
embedded_in :store
virtually_have_many :products # here I want a virtual collection
end
class Product
include Mongoid::Document
field :name
embedded_in :store
virtually_belongs_to :categoryend
MongoDB:
{_id: 1, name: "2TB HardDisk", category: 2},
{_id: 2, name: "Apple", category: 1}
{_id: 1, name: "Vegetables", products: [2]},
{_id: 2, name: "Electronics", products: [1]}
As you can see, each Categories has a list of products' id. I think this solution should be faster then storing Product and Category in separate collections, isn't it? Only one call should be done to Mongo, instead of (at least) 3 to retrieve a full Store object (I need it in the products list, one of the most visited part).
Before anything, if you think there's a better way to achieve this, share it and thank you :P
I would like to code a ruby gem that do exactly this, using an interface like the one proposed, but even if I've already done some coding to achieve this (still messy, with code in the models instead of a clean module), I don't really know how to directly integrate it as a gem (module), more precisely, how to create a relation of this kind. Someone can give me some tutorial/guidelines or some info on how "have_many" works?
Thank you,
Iazel