2015-04-06 86 views
0

這裏仍然是新手,但我仍然無法獲得正確的邏輯。Ruby Active Record關係

目前,我有:

  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 

這是我迄今所做的。它仍然看起來不太正確,因爲我同時感到困惑。非常感激你的幫助! :)

+0

您需要的has_many:通過ASSOCATION。看看http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association – Klaus

回答

2

定義三種模式:

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