Seeding Your Phoenix App For Different Mix Environments

By default when creating a new Phoenix app, a seed.exs file is automatically created for you in the priv/repo/ directory. Additionally, the mix.exs file has an alias for seeding your database that looks like this:

defp aliases do
  [
   "setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
   "reset": ["ecto.drop", "setup"]
  ]
end

All you have to do to setup your environment is execute mix setup or mix reset.

This code, however, is not Mix environment aware. Some seeds that you have for development should not be applied to your production database. Chris McCord in a Github issue recommends creating an actual Mix Task for having different seeds based off environment.

The Mix Task###

Create a file called seed.ex somewhere in your lib directory. Now use the following as a starting template for your seeds:

defmodule Mix.Tasks.MyApp.Seed do
  use Mix.Task
  alias MyApp.Repo
  import Ecto

  def run(_) do
    Mix.Task.run "app.start", []
    seed(Mix.env)
  end

  def seed(:dev) do
    # Any data for development goes here
    # i.e. Repo.insert!(%MyApp.User{}, %{ first_name: "Alex, last_name: "Garibay" })
  end

  def seed(:prod) do
    # Proceed with caution for production
  end
end

Now update your mix.exs to use the new task in the aliases method:

defp aliases do
  [
   "setup": ["ecto.create", "eco.migrate", "myapp.seed"],
   "reset": ["ecto.drop", "setup"]
  ]
end

That's it! Your seeds are now based on the mix environment when you run mix reset or mix setup.

#phoenix   •   #elixir   •   #ecto