Rails/Relationships/Recommendations

Gang,

Having a bit of trouble conceptually pulling something together in
rails. Imagine the following:

I have Users
I have Products
I have Purchases

A Purchase is simply a user -> product + timestamp relationship. So,
User A bought Proudct B on date X.

Currently, my data model is extremely trivial:

user: id, username, password
products: id, name, price, etc.
purchases: id, user_id, product_id, timestamp

What I’m looking to do is say, “Welcome, User A, you purchased these
products in this time range.” What I’m struggling with is the correct
relationship structure. Obviously a User has_many purchases, but does a
Purchase belong_to a User? I assume so. Does a Purchase have_a
(has_one) User? Does a Purchase have_a (has_one) Product? Do Products
have_many Purchases?

A little direction would be most welcome. Hitting the books now.

This is basically an example of a n to n relationship. User and Product
have n to n relationship.
The Purchase is the entity that breaks this relationship into one to
many and many to one.
So you will have one to many between a user and a purchase and many to
one from purchase to
product.

You don’t need the id in the purchases table because it is a join table
and the key consists of
the user_id and product_id

Hi Cory, I would recommend viewing the example in AWDR because it uses a
similar model.

Good luck,

-Conrad

Hi Cory, I was thinking along the following lines where a ‘Purchase’ is
really an ‘Order’:

User has_many Order
Order belongs_to User
Order has_many Products
Product belongs_to Order

Next, I would associate a timestamp to an Order for simplicity because
everytime you
make a purchase that has 1 or more Products one creates an Order which
has
an Order
id and time of purchase. Well, I must go and I wish that this helps.

Peace,

-Conrad