1

For practice I'm writing a shopping website where we have tables User and Item. A user obviously has_many items (when they are added to their basket), but the item, it belongs_to a User, even though many users will have the same item in their basket?

Furthermore, what if I want a list of items a user has added to their basket, but also a list of items they have viewed (for making suggestions based on searches), would it be better to have some 'through' tables: Basket and Viewed?

1
  • You could create a polymorphic association for temporary items if your viewed is a "recently viewed". Create a separate model for these temp items and it would need to include user_id and item_id. Commented Feb 16, 2013 at 20:49

2 Answers 2

2

When you have this many-to-many relationships, you can use the HABTM schema:

Class User...
has_and_belongs_to_many :items

However, most of the time webshops use orderlines to keep up with items that users are purchasing. This means that an 'user' 'has_many' 'orderlines', an 'item' 'has_many' 'orderlines', an 'orderline' 'belongs_to' an 'user' and to an 'item'.

And maybe your orderlines will just be copies of items, and won't have a direct link because you don't want to alter the orderline after they have been processed. It really depends on the focus of your shop which scheme suits your needs.

Try to find some examples on the web and think about how you want to handle items, orders and baskets.

Sign up to request clarification or add additional context in comments.

1 Comment

Take a look at the book Agile Web Development with Rails. The book helps you build a shopping website and explains the order lines mentioned in the answer above.
0

I'm used to separate things that are not the same, even if the relationship is one-to-one. So first of all I would recommend users from baskets (1:1-relationship).

After that a basket contains many items and items can be in multiple baskets (m:n-relationship). Make sure, that maybe a user likes to buy the same item multiple times.

views can be realised as a linking table between users and items: users have many views and items have many views, but one view is always linked to exactly one user and one item.

1 Comment

Thanks for the tip about multiple items

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.