Ruby on rails 在Rails中为商店建模

Ruby on rails 在Rails中为商店建模,ruby-on-rails,ruby-on-rails-3,activerecord,mapping,Ruby On Rails,Ruby On Rails 3,Activerecord,Mapping,想象一下一个商店模型,其中一个商店可以有许多项目,每个项目可以有不同的价格,这可能因商店(不同的商店可以有相同的项目,但价格不同) 这正是商店在现实生活中的表现 到目前为止,我有商品、商店、和价格作为模型 我将如何在Rails中对这种关联进行建模?添加/删除模型不是问题 我还需要此关联,以方便我进行此类查询: “给定商品(或商品id),返回包含该商品的门店列表,包括其价格” 到目前为止,我有以下联系: Store: has_and_belongs_to_many :items Item:

想象一下一个商店模型,其中一个
商店可以有许多
项目
,每个
项目
可以有不同的
价格
,这可能因
商店
(不同的商店可以有相同的项目,但价格不同)

这正是商店在现实生活中的表现

到目前为止,我有
商品
商店
、和
价格
作为模型

我将如何在Rails中对这种关联进行建模?添加/删除模型不是问题

我还需要此关联,以方便我进行此类查询:

“给定商品(或商品id),返回包含该商品的门店列表,包括其价格”

到目前为止,我有以下联系:

Store:
  has_and_belongs_to_many :items
Item: 
  has_and_belongs_to_many :stores
  has_and_belongs_to_many :prices
Price:
  has_and_belongs_to_many :items

我会用has\u many:通过,而不是has\u和\u属于\u many

商店零售商品

Store
has_many :items through :retails
has_many :retails

Retail
belongs_to :store
belongs_to :item

Item
has_many :stores through :retails
has_many :retails

然后,您可以向retails表中添加一个价格,即每家商店的每种商品的价格。

第四种模式是StorePrices,它允许通过
关系建立多个

Item:
  has_many :store_prices
  has_many :stores, :through => :store_prices

Store:
  has_many :store_prices
  has_many :items, :through => :store_prices

StorePrice:
  belongs_to :store
  belongs_to :item
商店价格表如下所示:

id -> integer
store_id -> integer
item_id -> integer
price -> decimal
stores = item.stores
您可以获得给定商品的商店,如下所示:

id -> integer
store_id -> integer
item_id -> integer
price -> decimal
stores = item.stores
第一家店的商品价格:

price = item.store_prices.first.price

为什么我需要
有很多:在
项目中存储价格
存储
?它完成了什么?它告诉模型你与商店价格模型有一对多的关系,它将你的独特商品价格与它们所在的商店“粘合”在一起。看见