Ecto
Handles external data such as databases and JSON APIs
- Repo
- Query
- Schema
- Changset
Repo: communicates with external data source or database
Has common methods:
- get(): gets the record
- insert(): creates the record in that database
- update()
- delete()
- transaction() …
Phoenix uses Repo through:
config.exs
as config:appname, Appname.Repo,
…repo.ex
in/lib/appname/repo.ex
Common methods
Repo.count()
Repo.update_all("tablename", set: [updated_at: Ecto.DateTime.utc])
Schema
Reusable data-model for moving data around. Schemas are a useful shortcut used in querying so you don’t have to specify all the attributes
Schema Associations
sets relationships between tables
- has_many
- has_one
- belongs_to
- many_to_many
Virtual Attributes
Disposable attributes that are not saved to the database. For example, an office address that is used to get a latitude and longitude to store in the database, without storing the office address
Embedded Schema
A schema that doesn’t use a datbase
Changeset
Allows manipulation of the data to match Schema so that it can be passed to the Repo
- Cast: filters the parameters with the attributes to be accepted into the changeset
- Validate: validates those filtered attributes. This includes constraints which are set on the database level
Defining
def changeset(schemaname, attrs) do
schemaname
|> cast(attrs, [:key1, :key2,..])
|> validate_required([:key1])
|> validate_inclusion(:name, ["John", "Jack"])
|> validate_exclusion(:name, ["Jub Jub"])
|> validate_length(:country, is: 2)
|> validate_length(:password, min: 8, max: 32)
end
Calling
attrib_name = get_field(changeset, :attrib_name)
Schemaless Changeset
Defining
model = %{key1: :string, key2: string}
attributes = %{key1: "value", key2: "value"}
changeset = {%{}, model}
|> cast(attributes, Map.keys(model))
|> validate_required([:key1])
end
Ecto Queries (see other article)
Phoenix
Phoenix Ecto
allows changeset shortcuts into forms