2015-11-02 27 views
0

我正在使用rails來構建一個應用程序,其中所有者擁有許多產品。每個產品都可以在需要時轉讓給其他所有者。如何實現模型的「轉讓所有權」的數據結構

在我的第一個想法我想象的簡單關係

Owner has_many :products product belongs_to owner

當我需要添加一個MANY_TO_MANY關係,我想可能是我可以添加一個owners_products_table。但是我無法區分每個所有者擁有產品的時間。

我想有添加列像start_owning_atend_owning_at ..但它似乎讓所有的查詢過程很麻煩..

我不知道如何可以實現所有權轉移數據的關係?

回答

2

因此,您需要跟蹤每個用戶擁有產品的時間段?我認爲你對如何建模的本能是正確的,你可以努力使查詢簡單直觀。

我會對此建模像這樣:

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字段設置爲切換時間。

相關問題