Search⌘ K
AI Features

Create Resource

Explore how to create products and their variants in a Rust web application using Diesel for database migrations and data insertion. Learn to build normalized tables, manage data relationships, and write test functions to ensure your product creation logic works correctly.

We'll cover the following...

Create a product

We can start creating the migration needed for our project. We can name it however we want. Let’s call it create_products to add the migration necessary to create and drop our table.

Note: After we install and configure Diesel according to the first Appendix, we can write the following command in a terminal window:

Shell
diesel migration generate create_products

The previous command will create two files named up.sql and down.sql inside the migrations folder.

We’ll enter the below code in the up.sql file.

MySQL
CREATE TABLE products (
id INTEGER PRIMARY KEY,
name VARCHAR NOT NULL,
cost DOUBLE NOT NULL,
active BOOLEAN NOT NULL DEFAULT 0 --Sqlite does not have a Boolean value
)

Let’s work with the down.sql file now.

MySQL
drop table products

Now, we can run our migration to create the products table by running the following command in the terminal:

Shell
diesel migration run

We add a file called models.rs for our ...