Validating the Product Model

Learn how to add the validation rules for products' parameters.

Validation is an essential part of building any application and prevents junk data from being saved onto the database.

Create validation rules

In the Product model, we have to ensure that the price is a number and is not negative. Another important validation is that every product should have a user. In this case, we need to validate the presence of the user_id.

We have added the code to app/models/products.rb, as follows:

Get hands-on with 1400+ tech skills courses.