Search code examples
elixirphoenix-frameworkecto

How to insert default data into an Ecto database?


I have a table which contains the job types that can be created, and a migration and schema to go with these, however I would like to insert default data into the table on migration / creation.

Currently, I resort to just adding the data myself and hoping I don't accidentally rollback too far, but I would like a more robust solution to this.


Solution

  • These are called "seeds".

    In your mix.exs, create an alias like this:

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

    Now just create that file priv/repo/seeds.exs and put something like this in it:

    case Mix.env() do
      :dev ->
        IO.puts("Let's add some data!")
        {:ok, job_0} = YourModule.create_job(%{name: "job_0"})
        {:ok, job_1} = YourModule.create_job(%{name: "job_1"})
    
      _ ->
        nil
    end
    

    Note that I am careful to only run "seeds" in the :dev environment.

    With all this setup, you can just do mix ecto.drop to drop the current database and then mix ecto.setup to create a new database, run migrations and populate with seed data.

    What I have written is purely illustrative. You are free to make any kind of mix alias and seeds script you want.