Ask A Question


You’re not receiving notifications from this thread.

How to setup the model associations for a simple e-marketplace?

Robert Paul asked in Rails

Hey GoRails devs,

I am in the middle of setting up a marketplace (with stripe) and could use some help in conceptually thinking about the model associations. In the marketplace: a user can sell or buy a book, and there is no cart system. If a user wants to buy a book they just click "purchase book" on a book show page.

Here's one way I thought of:

For the Book model, attributes of:

    sold_by :integer (user id of seller)
    bought_by :integer (user id of person buying)
    name :string
    author :string

or, another way is setting up a model just to handle the seller/buyer purchase relationship, but I'm not sure how that would look. Thoughts? This is a new challenge for me.


Quick question first, are you going to be handling inventory? Like will there be X number of this book?


Hey Chris. It'd just be one book at a time.

Edit: No, there would not be an inventory system. A book create action would only create one new book in the database.


Cross posting this from Slack:

I think your setup looks alright. Any books where the bought_by is nil means it’s not been sold. When you do checkout you can charge the user and then assign the ID there and it can go off the market.

If someone else was in the process of buying the book at the same time, you can wrap that in a transaction so that when the assign of the ID fails, you can refund the purchase or vice versa. Assign the id first and attempt payment, then undo the ID if the payment fails. Probably that second way would make the most sense (checkout the transactions video I did recently for more on those rollbacks) not having inventory means you get a LOT of simplicity which you wouldn’t otherwise.

Another thing here is that you don’t need an “Order” model or a cart or anything because you can use the book itself for all that information. So you buy it, and the seller ships it and wants to add tracking, you can then just put it on the book if you wanted or associate a shipping record to that book.

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,329+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.