2012-05-03 5 views
0
に格納モデリング

storeitems多くを有することができ、各itemは(異なる店舗が同じ項目が異なる価格を有することができる)storeによって異なることができるprice異なるを有することができ、店舗モデルを想像。レール

これは実際の店舗での店舗の正確さです。

これまでのところ、itemstorepriceをモデルにしています。

Railsでこの関連付けをどのようにモデル化できますか?モデルの追加/削除は問題ありません。

私も、この協会は、簡単なクエリを実行するために私を可能にする必要があります:

「のアイテム(またはアイテムのID)を考えると、その価格を含めて、このアイテムを運ぶ店のリストを返します」。そして、あなたが追加することができます

店を通じて小売アイテム

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 

代わりに、私はにhas_manyを使用するhas_and_belongs_to_manyアソシエーションを使用しての
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 

答えて

2

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

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

そして、あなたはこのような特定のアイテムのために店を得ることができます::

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テーブルには、次のようになり

stores = item.stores 

最初のアイテムの価格ストア:

price = item.store_prices.first.price 
+0

なぜ私は 'has_many :Store_prices'を 'Item'と' Store'に入れますか?それは何を達成するのですか? – ryanprayogo

+0

これは、モデルに、store_pricesモデルと1対多の関係があることを示します。これは、固有の商品価格を見つけた店舗に「接着」します。http://guides.rubyonrails.org/association_basics.htmlを参照してください。 –

0

は:

はこれまでのところ、私は、次の関連付けを持っています店舗ごとのアイテムごとになる小売りテーブルへの価格。