← All series

Series contents

Log in to track your progress

  1. 1. Ecto Overview: The Repo Episode
  2. 2. Configuring a new project with Ecto Episode
  3. 3. Creating Ecto Migrations Episode
  4. 4. Schema-less Ecto Queries Episode
  5. 5. Our first Ecto schemas Episode
  6. 6. Some useful Ecto functions Episode
  7. 7. Configuring IEx for working with Ecto Episode
  8. 8. Ecto belongs_to and has_many Episode
  9. 9. Ecto many_to_many and joining through Episode
  10. 10. Naming things in an Ecto project Episode
  11. 11. Ecto changesets: change vs cast Episode
  12. 12. Ecto changesets, validations and constraints Episode
  13. 13. Ecto build_assoc and put_assoc Episode

Configuring a new project with Ecto

For this project, we'll be working with a plain Elixir mix project without Phoenix.

Creation and deps

To create it, enter the following from the terminal:

mix new linkly --sup
cd linkly

We need the --sup flag so that the project has a supervisor. This is for Ecto. Next, open up your project in your favorite editor, open the mix.exs file and then add Ecto and Postgrex (a Postgres library) to your project's deps:

defp deps do
  [
    {:postgrex, ">= 0.0.0"},
    {:ecto_sql, "~> 3.1"}
    # {:dep_from_hexpm, "~> 0.3.0"},
    # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
  ]
end

To fetch the deps, run

mix deps.get

Creating the repo

Create a repo file in the lib/linkly directory called, repo.ex and add the following contents to configure your Ecto repo:

defmodule Linkly.Repo do
  use Ecto.Repo,
    otp_app: :linkly,
    adapter: Ecto.Adapters.Postgres
end

The repo also needs to be added into the supervision tree of the app, inside the start function in application.ex.

  def start(_type, _args) do
    children = [
      Linkly.Repo

Configuration

Mix projects no longer generate configuration files by default, but we need some configuration in order to connect to a database. Create a config directory at the top level of your project and then a config.exs file in it to hold your default configuration and a dev.exs to hold the dev environment-specific configuration.

In config.exs, we'll add the ecto repos config and import the appropriate config for our environment:

use Mix.Config

config :linkly, :ecto_repos, [Linkly.Repo]

import_config "#{Mix.env()}.exs"

We'll put off creating the prod.exs and test.exs config files for now and just create a dev.exs with our database credentials:

use Mix.Config

config :linkly, Linkly.Repo,
  username: "postgres",
  password: "postgres",
  database: "linkly_dev",
  hostname: "localhost"

Open standalone page ↗

No Comments