Schema Integration with Database

Learn how to update our schema to work with the database.

We’re now ready to update our schema to match this table.

Updating our schema for database

Technically we’ll update a copy to the schema to make changes without breaking our other test files.

Let’s copy testing_ecto/lib/schemas/user_basic_schema.ex to a new file called testing_ecto/lib/schemas/user_database_schema.ex. We’ll copy the test file to match later. For now, we’ve updated the schema file to look like this:

Note: The changes are consolidated for you in the below-given widget. Simply replace the contents in the specified file.

Press + to interact
#file path -> testing_ecto/lib/schemas/user_database_schema.ex
#replace the code at the indicated place mentioned in comments of testing_ecto/
#lib/schemas/user_database_schema.ex in the playground widget
defmodule TestingEcto.Schemas.UserDatabaseSchema do
use Ecto.Schema
import Ecto.Changeset
@timestamps_opts type: :utc_datetime_usec
@primary_key {:id, :binary_id, autogenerate: true}
@optional_fields [:id, :favorite_number]
schema "users" do
field(:date_of_birth, :date)
field(:email, :string)
field(:favorite_number, :float)
field(:first_name, :string)
field(:last_name, :string)
field(:phone_number, :string)
timestamps()
end
defp all_fields do
__MODULE__.__schema__(:fields)
end
def changeset(params) do
%__MODULE__{}
|> cast(params, all_fields())
|> validate_required(all_fields() -- @optional_fields)
|> unique_constraint(:email)
end
end

Let’s look at what changes we have made to our code ...