【问题标题】:Using models and migrations in code在代码中使用模型和迁移
【发布时间】: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


【解决方案1】:

如果您需要存储价格历史记录以获取最新价格或类似信息,恐怕您当前的 products_shops 表不会很有用

您可以创建一个单独的Price 模型和prices 表,其中包含假设product_idshop_id 和实际price。模型看起来像

class Price < ApplicationRecord
  belongs_to :product
  belongs_to :shop
end

has_many :prices 关联添加到productsshops 可能很有用:

class Shop < ApplicationRecord
  has_many :products
  has_many :prices
end

class Product < ApplicationRecord
  belongs_to :shops
  has_many :prices
end

然后您就可以为每对商店和产品保存多个价格,获取每个产品的所有价格等等

例如,获取特定商店中产品的所有价格(即商店中产品的价格历史记录):

Price.where(product_id: your_product_id, shop_id: your_shop_id)

Price.where(product_id: your_product_id, shop_id: your_shop_id).order(:created_at).last 将给出商店中产品的最新价格。

【讨论】:

    猜你喜欢
    • 2014-12-01
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多