Premium Content - Free Preview
Your console store app can be used to perform all sorts of actions, including ones that shouldn't be valid. For example, let's say we create a product in the rails console without any information in it:
prod = Product.create
(0.2ms) begin transaction SQL (0.7ms) INSERT INTO "products"... (1.4ms) commit transaction => #<Product id: 9, name: nil, description: nil, price: nil, ... >
This just saved a product to the database with no values filled in. This is not only useless, it can cause bugs when other code expects certain values to exist in a product, such as a product's name. Go ahead and destroy the product just created:
To prevent an invalid product from being created, we should add code to validate our data before it is saved. Rails provides a
validates method for this purpose. Add the
validates line to your Product model:
class Product < ActiveRecord::Base validates :name, presence: true belongs_to :category end
validates method takes in parameters for the column and the property you're ensuring, such as the name and presence.
Now that we've ensured every product will have a name, let's make sure every product has a price. Enter the code to do that below and in your Product class.
Reload your console and try to create an empty product like before.