Schema Best Practice: Is it ever OK to store duplicates of a record?

时间:2015-12-04 21:18:47

标签: ruby-on-rails postgresql schema

This is a general question about good schema design. In my case I'm using Rails 4 and PostgreSQL.

Let's say I have a storefront, with many products. The store also has many orders, each with many products.

On Monday, a customer pays for an order. So now, we have a product that belongs to both a storefront and an order.

On Tuesday, the store decides to change the price of one of the products.

Clearly, I don't want to change the record of what the customer purchased on Monday, so this leads me to believe I should store two copies of the product - one copy of what the store is selling now (ie Tuesday), another copy for what the customer bought on Monday.

However, I know that duplicating data like this something generally to be avoided.

Is there a best-practice for handling a situation like this?

1 个答案:

答案 0 :(得分:2)

这听起来像是重复,因为你为它们使用相同的名称。一个价格是客户支付的价格。另一个是产品目前销售的价格。即使在很多情况下它们具有相同的值,它们也会分离数据。我只是给他们单独的名称(例如Order#paid v。Product#price),并在销售时将Product#price存储在Order#paid。这样可以在不影响订单的情况下改变产品价格。