Ecto is way more than database migrations.
To start inserting data into the database and querying on tables, we will need an Ecto model.
To made a module an Ecto model, you need to
import Ecto.Query and then provide a schema.
The schema information is used to map a database table and its columns to a module and its struct.
Post model is defined as:
# /web/models/post.ex defmodule Readdit.Post do use Readdit.Web, :model import Ecto.Query schema "posts" do field :title, :string field :votes, :integer field :flagged, :boolean field :posted_on, Ecto.DateTime timestamps end end
No Table Name Conventions
schema "posts" tells our Ecto model which table to connect to. While our
Post model is connected to the
posts table, there is no naming requirement for matching a table with a model.
This is awesome. This means that it is easy to create different models on the same database table. It also means that connecting to a legacy database with table names like
tblPosts is easy and the database naming conventions won’t bleed into your application.
Field Type is different than Database Type
When creating the schema mapping, we specify the type of the field. This field type is different than the database type. If you had a database field of
text type, you would specify the type as
string for the model. This is because there is no
text type in Elixir.
There are built in conversions for some database types to Elixir types, but you can also create your own custom type conversion (which we will cover when we add JSON fields to our table).
For ease of querying, it is recommended to use
Ecto.DateTime types for your
datetime database fields.