Rails-对实体之间的复杂关系进行数据建模



我正在用Rails编写一个软件。模型之间的两种关系让我对属性应该驻留在哪里感到困惑。这是一个非典型的定价场景,涉及销售给某些客户的产品价格。根据客户的不同,我们的产品可能会以不同的价格出售。我们卖给的一些大公司已经通过谈判把我们的价格降低了一点。

General Pricing Applicable to most customers
Product A -> $50
Product B -> $60
Product C -> $70

因此,在这种情况下,很容易说产品具有价格属性。然而,该公司已经与一些大客户协商了价格,这些客户可能会出现以下情况。

ACME Corporation
Product A -> $45
Product B -> $56
Product C -> $64
ABC Incorporated
Product A -> $43
Product B -> $55
Product C -> $66

这些价格是经过协商的,而不是基于原始价格的折扣百分比。这带来了一个问题,即每种产品都可能有许多价格,具体取决于客户。我该如何建模。在大多数用例下,以下工作。

Customer has_many :quotes
Quote belongs_to :customer
Quote has_many :quote_items
QuoteItem belongs_to :quote
Product has_many :quote_items
QuoteItem belongs_to :product

但是,由于产品的价格可能因客户而异,这是如何建模的?例如,产品是否与客户有多对多的关系?

不确定基础设施是如何布局的,但这里有一个想法。

Customer has_many :products
Product belongs_to :customer

只需转到产品模型并创建一个"报价"属性。

然后你可以做例如

ACME.ProductA.quote
=> $45

编辑(添加更多)

嗯,你得详细说明。。。事实上,如果你想获得产品A的所有实例的库存,只需做一些类似(概念上)的事情

listOfProducts = Product.find_by_<name>("productA") 
for each productA from listOfProducts 
print productA.quote 

如果你想进一步获得产品的客户,你可以通过URL解析来跟踪客户的ID

我提出的解决方案是产品和客户之间的多对多关系,并使用名为product_customers的查找表来跟踪价格属性。不确定这是否是最优雅的方法,但它可以将重复降至最低。缺点是处理表单的复杂性增加。如果有人提出一个更优雅的答案,我会给他们打分。

Customer has_many :products, :through => :customer_products
Customer has_many :customer_products
Customer has_many :quotes
Quote belongs_to :customer
Product has_many :customers, :through => :customer_products
Product has_many :customer_products
Product has_many :quote_items
QuoteItem belongs_to :product
CustomerProducts belongs_to :customers
CustomerProducts belongs_to :products
Quote has_many :quote_items
QuoteItem belongs_to :quote

最新更新