【发布时间】:2014-05-02 10:36:23
【问题描述】:
我正在开始一个带有 产品、客户和卖家的 Rails 项目。每个卖家has_many products。每个客户has_many products。 (就我而言,每个客户一次只购买一种产品)。
我想知道谁是我的客户的卖家和我的卖家的客户,我知道,他们将通过购买一种产品联系起来。
我应该在客户和卖家之间使用has_and_belongs_to_many 关联吗?或者双 has_many through :products,比如:
卖家:
has_many :clients through :products
Belongs_to :products
客户:
has_many :sellers through :products
Belongs_to :products
为了避免product 类中有两个belongs_to,这样可以吗?
class Client < ActiveRecord::Base
has_many :products, as: :productable
has_many :sellers, through: :products
end
class Seller < ActiveRecord::Base
has_many :products, as: :productable
has_many :clients, through: :products
end
class Product < ActiveRecord::Base
belongs_to :productable, polymorphic: true
end
提前感谢您的回答。
【问题讨论】:
-
首先,在这两个模型和 Product 中都应该是
has_and_belongs_to_many :products。因为它是多对多的关系 b/w 客户-产品,卖家-产品。 -
事实上,每个产品都是独一无二的。就好像他们是画,卖家是画家。每个画家可以创作/创作多幅画,但一幅画只有一个画家,而且只有一个客户。但是客户可以从画家那里购买许多画作。
标签: ruby-on-rails activerecord associations has-many-through