Getting started with Elixir’s Ecto coming from Ruby’s ActiveRecord

Jul 3 · 2 min read

Before we begin I should mention that the version of Phoenix I’m running this tutorial on is 1.4.8 which is the latest version at the time of writing.

You can configure Phoenix to connect to which ever databases you like, there files are located in the config :

use Mix.Config# Configure your database
config :app, App.Repo,
database: "app_development",
hostname: "localhost",
show_sensitive_data_on_connection_error: true,
pool_size: 10

This is useful if you wish to connect to an application’s database on which you’re rewriting.

Getting into the rails console equivalent:

In your project directory you can type: iex -S mix .

In our examples we’ll use App to refer to the name of your Phoenix project application module name. Ecto has solid documentation on writing queries. But to get started here’s a simple one:

query = from u in “users”, select: {,}

You’ll get undefined function from if you call it without running import Ecto.Query first which will include the from method.

Once you’ve built the query we can then call App.Repo.all(query) . Another way to run this statement is Elixir’s pipe operator:

query |> App.Repo.all

You can generate a schema file for a table by running mix phx.gen.schema User users name email created_at:utc_datetime updated_at:utc_datetime .

For a list of primitive types supported by ecto, see:

If you wish to reload any module in iex you can run r App.User for example.

This is great — but if you’re creating models for an existing template you probably want to delete your migrations that it generates and use your existing schema. You can do so by running running the following mix command:mix ecto.dump


Written by


Connecting the world, keeping it safe. Senior Engineer @, CEO @