I know this is a (somewhat) common question but I'm a newbie and I always appreciate a second (or 100th) pair of eyes on a problem I'm been noodling.
I'm wondering if I'm taking the right approach here -- I'm trying to model a product with several variations and the associated gift certificates sold against that product.
A product, for example, for a restaurant might be a "tasting menu for 2" whereas variations might be "food only", "with partial wine pairing", and "with full wine pairing", etc. (just an illustrative example).
Here's a distilled version of what I've come up with:
class Product
include Mongoid::Document
field :name, type: String
has_many :gift_certificates
embeds_many :variations
end
class Variation
include Mongoid::Document
field :name, type: String
embedded_in :product
has_many :gift_certificates
end
class GiftCertificate
include Mongoid::Document
field :recipient, type: String
field :amount, type: Float
belongs_to :product
belongs_to :variation
end
So when we create a GiftCertificate, it's defined as belonging to both a product and a variation (is that correct?). An example might be a "$200 gift certificate for tasting menu for 2 [product] with partial wine pairing [variation]", etc.
I feel like the embeds_many / embedded_in relation here for Products/Variations is ideal as it fits the profile for when it should be used: I'll never be accessing a product without its variation, and I never need to access a variation independant of a product -- they go hand-in-hand.
So the question is whether I'm doing this the right way.
I've managed to massage the basic CRUD forms into working using ryanb's excellent nested_form gem, with a bit of tweaking. Editing the Products & Variations are easy (the basic use case), but the trouble I'm having comes when working with the Gift Certificates.
Mongoid is giving me a bit of trouble ... the GiftCertificate belonging to both a product and its variation seems kludgy, and I have to manually set the GiftCertificate.variation each time I do a find, i.e.
@gc = GiftCertificate.find(params[:id]) // as normal
@gc.variation // ==> nil, doesn't work by itself
@gc.variation = @gc.product.variations.find(@gc.variation_id) // Have to manually set this
@gc.variation // Now this works as it's supposed to
Anyway, before I go on -- would love to get some thoughts on the above.
Thanks in advance!