Generating the Product Model

Generate the Product model for the application.

We now have a straightforward implementation of the User model, but the moment of truth has come. We will customize the JSON output and add a second resource: the user’s products. These are the elements that the user will sell in the application and will be directly linked.

If you are familiar with Rails, you may already know something about this. For those who don’t know, we will associate the User model with the Product model using the has_many and belongs_to methods of Active Record.

In this chapter, we will perform the following actions:

  • Build the Product model from scratch.
  • Associate it with the user.
  • Create the necessary entries so any customer can access the information.

We will first create a Product model. Then we’ll add some validations and, finally, associate it with the User model. Like the user, a product will be thoroughly tested and automatically deleted if the user is deleted.

The Product model will need several fields:

  • A title to define a product’s title.
  • A price attribute for the product’s price.
  • A published boolean to know if the product is ready to be sold or not.
  • A user_id to associate a particular product to a user.

Get hands-on with 1200+ tech skills courses.