Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pre-populate database on a Phoenix application start-up?

I have this schema:

schema "editables" do
    field :title, :string 
    field :content, :binary
   timestamps
end

I would like that on application start-up a few rows were automatically created and populated, say I want to create 6 entries with the :title field containing: page1, page2,... I should I do it?

like image 757
Paulo Janeiro Avatar asked Sep 16 '15 10:09

Paulo Janeiro


1 Answers

My suggestion: create an script file that will populate the database. Let's call it priv/repo/seeds.exs:

alias MyApp.Repo
Repo.insert! %MyApp.Data{...}
Repo.insert! %MyApp.Data{...}

In development you can run it as

mix run priv/repo/seeds.exs

or when you need in production:

MIX_ENV=prod mix run priv/repo/seeds.exs

I can't see any reason for you to do this every time the app starts. Imagine every command you run in development, test or production now needs to pay the penalty of creating data in the database. It is not a good idea.

like image 114
José Valim Avatar answered Nov 04 '22 12:11

José Valim