簡體   English   中英

Ruby活動記錄關系

[英]Ruby Active Record Relational

這里仍然是新手,但我仍然無法理解正確的邏輯。

目前,我有:

  1. 用戶有很多產品。
  2. 產品有1個具有價格屬性的用戶。

我正在嘗試添加:

  1. 用戶可以為另一位用戶出售的產品提供1個價格。 用戶可以提供多種產品的價格。
  2. 一個產品可以有多個用戶提供許多價格。

我目前有:

class User < ActiveRecord::Base
 has_many :products
 has_many :offered_prices
end

class Product < ActiveRecord::Base
 belongs_to :user
 has_many :offered_prices
end 

到目前為止,這是我所做的。 這似乎還不太正確,因為我同時感到困惑。 非常感激你的幫助! :)

定義三個模型:

User | OfferedPrice | Product

它們之間的關聯將是:

class User < ActiveRecord::Base
  has_many :products
  has_many :offered_prices, through: :products
end

class OfferedPrice < ActiveRecord::Base
  belongs_to :user
  belongs_to :product

  # To make sure a user can offer price once for against a product
  validates_uniqueness_of :price, scope: [:user, :product]
end

class Product < ActiveRecord::Base
  has_many :offered_prices
  has_many :user, through: :offered_prices
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM