我正在使用Rails来构建所有者拥有许多产品的应用程序。并且在需要时可以将每个产品转让给另一个所有者。
我最初的想法是想像一个简单的关系
Owner has_many :products product belongs_to owner
由于我需要添加many_to_many关系,所以我想可能可以添加owners_products_table
。但是,我将无法区分每个所有者拥有该产品的期限。
我以为添加了列,例如start_owning_at
。和end_owning_at
.. ,但这似乎使所有查询过程都非常麻烦。
我想知道如何实现转让所有权数据关系?
因此,您需要跟踪每个用户拥有产品的期限吗?我认为您对如何对其建模的直觉是正确的,并且您可以使查询变得简单而直观。
我会这样建模:
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) }
现在您应该能够说出类似
@owner = Owner.find_by_id(params[:id])
@products = @owner.products.current
#or
@products = @owner.products.at_time(Time.parse(params[:time]))
等等,或执行相同操作以列出product_ownerships而不是产品:例如,如果您有一个表单页面,用户可以在其中更新product_ownerships的时间,则此方法很有用。
编辑-顺便说一句,在这种模式下,当新的所有者购买产品时,您应该创建一个新的ProductOwnership,并将ownership_ends_at
旧所有者的字段设置为移交时间。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句