【发布时间】:2018-07-28 08:21:17
【问题描述】:
我试图解决一个我试图在 Ruby on Rails 应用程序中解决的问题,但经过三天的搜索和尝试,我似乎得到了隧道视野并被卡住了:
我有产品和商店,一个产品可以被许多商店出售。该产品的价格可能因商店而异,我想创建每个商店价格的历史记录,因此我想将价格信息保存在单独的表格中。
我创建了以下迁移:
class CreateProducts < ActiveRecord::Migration[5.2]
def change
create_table :products do |t|
t.string :name
t.text :description
t.string :ean
t.text :category
t.belongs_to :shop, index: true
t.belongs_to :lists, index: true
t.timestamps
end
create_table :shops do |t|
t.string :name
t.string :url
t.integer :priority
t.timestamps
end
create_table :products_shops do |t|
t.belongs_to :products, index: true
t.belongs_to :shops, index: true
t.float :price
t.timestamps
end
end
end
以及以下型号:
class Product < ApplicationRecord
belongs_to :shops
end
class Shop < ApplicationRecord
has_many :products
end
我的问题: 如何将价格信息保存到 products_shops 表中?以及如何将数据与产品一起检索回来,以便获得产品信息以及拥有该产品的所有商店以及每家商店的最新价格?
【问题讨论】:
-
您是否考虑过非规范化您的数据模型?将它们全部放在一个表中,然后创建另一个具有完全相同字段的表来存储历史记录。如果/当您的应用获得大量流量时,这也可能有助于进一步发展。
-
我将在产品表中添加一个最低进程字段,以防止每次产品视图都必须获得最低价格。在产品详细信息页面上,我将显示所有销售该产品的商店的价格。好建议!谢谢
标签: ruby-on-rails postgresql rails-migrations rails-models