Ecto Schema and Database Migrations
Define Ecto schemas to map Elixir structs to database tables and manage schema changes with migrations.
What is Ecto?
Welcome to Ecto! It's Elixir's powerful toolkit for interacting with databases. Think of it as your bridge between Elixir data and your database.
Ecto isn't a traditional Object-Relational Mapper (ORM). Instead, it's a data mapper. This means it focuses on mapping data between your Elixir application (using structs) and your database tables, giving you more control and less 'magic'.
Elixir Structs: Data Shapes
Before Ecto maps data to a database, Elixir uses structs to define data shapes. A struct is a special kind of map that ensures a predefined set of keys and default values.
Ecto schemas build upon this idea, extending structs to understand how their fields correspond to database columns.
Try running this simple struct example:
defmodule UserData do
defstruct name: "", age: 0, email: ""
end
# Create struct instances
user1 = %UserData{name: "Alice", age: 30}
user2 = %UserData{email: "bob@example.com"}
IO.puts "User 1: #{inspect user1}"
IO.puts "User 2: #{inspect user2}"
IO.puts "User 1's age: #{user1.age}"All lessons in this course
- Ecto Schema and Database Migrations
- Repo, Changesets, and Queries
- Associations and Embedded Schemas
- Transactions and Ecto.Multi