在Heroku上的Postgres存储浮动数组

时间:2013-10-17 19:50:37

标签: ruby-on-rails-3 postgresql heroku

我该怎么做呢?这是可取的吗?

我有一个名为“Item”的表,其中包含“name”和“price”列。

价格一直在变化,我想存储所有更改,以便我可以绘制它们。

我认为“价格”应该是一个阵列?这是对的吗?

由于

1 个答案:

答案 0 :(得分:2)

我会使用单独的表来跟踪价格历史记录。像这样简单:

create_table :item_prices do |t|
    t.integer :item_id, :null => false
    t.decimal :price,   :null => false, :precision => 7, :scale => 2
    t.timestamps
end

请注意,pricedecimal,而不是float。永远不要用浮点钱来赚钱。

然后在Item,像这样:

class Item
    has_many :item_prices
    before_save :update_price_history, :if => :price_changed?
private
    def update_price_history
        self.item_prices.create!(:price => self.price)
    end
end

这样做的一个很好的优点是,您可以跟踪价格何时发生变化以及价格本身,这可能会使您的图表看起来更加明智。