ryanprayogo
ryanprayogo

Reputation: 11817

Modelling a store in Rails

Imagine a store model where a store can have many items and each item can have different price which can differ by store (different stores can have the same item but different price).

This is exactly how store is in real life.

So far, I have item, store, and price as a model.

How would I model this association in Rails? Adding/removing models is not a problem.

I would also need this association to easily enables me to do such query:

"Given an item (or an id of an item), return the list of stores that carry this item including their prices".

So far, I have the following associations:

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

Upvotes: 0

Views: 95

Answers (2)

Paul Oliver
Paul Oliver

Reputation: 7681

What about a fourth model, StorePrices, which would allow a has_many :through relationship.

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

The store_prices table would look like this:

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

And you could get the stores for the given item like this:

stores = item.stores

The price of the item in the first store:

price = item.store_prices.first.price

Upvotes: 2

map7
map7

Reputation: 5126

Instead of using has_and_belongs_to_many I would use has_many :through

A store retails items

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

Then you could add a price to the retails table which would be per item per store.

Upvotes: 0

Related Questions