I am using rails to build an application where an owner owns many products. And each product can be transferred to another owner when needed.
At my first thought I imagine a simple relationship
Owner has_many :products product belongs_to owner
As I need to add a many_to_many relationship, I thought may be I can add a owners_products_table
. However I will not be able to distinguish the period of when each owner owns the product.
I thought have adding columns like start_owning_at
, and end_owning_at
..but it seems to make all the query process very troublesome..
I wonder how I can implement the transfer ownership data relationship?
So, you need to keep track of the period for which each user owns a product? I think your instinct about how to model it is correct, and you can work on making the queries simple and intuitive.
I would model this like so:
Owner
has_many :product_ownerships
has_many :products, :through => :product_ownerships
Product
has_many :product_ownerships
has_many :owners, :through => :product_ownerships
#some named scopes for convenience
scope :at_time, ->(time) { where("product_ownerships.ownership_starts_at <= ? and product_ownerships.ownership_ends_at => ?", time, time)}
scope :current, -> { at_time(Time.now) }
ProductOwnership
belongs_to :owner
belongs_to :product
#fields: product_id, owner_id, ownership_starts_at, ownership_ends_at
#some named scopes for convenience
scope :at_time, ->(time) { where("product_ownerships.ownership_starts_at <= ? and product_ownerships.ownership_ends_at => ?", time, time)}
scope :current, -> { at_time(Time.now) }
Now you should be able to say things like
@owner = Owner.find_by_id(params[:id])
@products = @owner.products.current
#or
@products = @owner.products.at_time(Time.parse(params[:time]))
etc, or do the same to list product_ownerships rather than products: this is useful if you have a form page where the user can update the times of the product_ownerships, for example.
EDIT - btw, in this schema, when a new Owner takes a product, you should make a new ProductOwnership, and set the ownership_ends_at
field for the old owner to be the handover time.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments