因此,您需要跟蹤每個用戶擁有產品的時間段?我認爲你對如何建模的本能是正確的,你可以努力使查詢簡單直觀。
我會對此建模像這樣:
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
字段設置爲切換時間。