0

店舗モデルを想像してみてください。1つの店舗storeが多くの店舗を持ち、itemsそれぞれitemが異なる店舗を持つことpriceができますstore(店舗によって同じ商品でも価格が異なる場合があります)。

これはまさに、実際の店舗のあり方です。

これまでのところ、モデルとしてitemstore、およびがあります。price

この関連付けを 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
4

2 に答える 2

2

関係を可能にする 4 番目のモデル、StorePrices はどうでしょうかhas_many :through

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

store_prices テーブルは次のようになります。

id -> integer
store_id -> integer
item_id -> integer
price -> decimal

そして、次のように特定のアイテムの店舗を取得できます。

stores = item.stores

最初の店舗での商品の価格:

price = item.store_prices.first.price
于 2012-05-03T03:19:21.680 に答える
0

has_and_belongs_to_many を使用する代わりに、 has_many :through を使用します

商品を販売する店

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

次に、店舗ごとの商品ごとの価格を小売テーブルに追加できます。

于 2012-05-03T03:16:14.520 に答える