Conveniently, when following this convention, Phoenix makes sure that our models are appropriately initialized; and as long as we use the bang functions (e.g., insert! , update! , etc.), they will also fail if something goes wrong.
So in order to seed data, we simply need to add a script to seeds.exs that uses our datastore to directly add the data we want. As you can see from the comments that Phoenix generated for us in seeds.exs file, we should follow this pattern:
This is nice for experimenting in IEx during development in many cases.
This is helpful, since it means that if we make a programming error (e.g., attempting to add a duplicate entry to a table where the field is required to be unique), the data in our database wonвЂ™t lose its integrity. The database will refuse to execute the query and Ecto will throw an exception, such as:
Now, we could add links trivially to our database in IEx like so:
For example, if we were creating an app called Linker and wanted to seed a Link table in our datastore with with a series of links, we could simply add the following script to our seeds.exs file:
When creating an app, itвЂ™s important that weвЂ™re able to seed our datastore with some initial data (e.g., for early development work or pre-launch testing purposes).
Note that if we wanted to delete/scrub all prior data that we seeded in the Link table, we could also include Repo.delete_all Link in your script immediate above Repo.insert!
Also note that in order to seed data as in the example below you should have already generated and run the related migration (i.e., Link migration, controller, model, etc.) and updated your router.ex , as described in the Ecto Models Guide (if you havenвЂ™t completed that Guide yet, you should do so before proceeding further).
Phoenix v1.3.0-rc.3 Seeding Data When creating an app, itвЂ™s important that weвЂ™re able to seed our datastore with some initial data (e.g., for early development work or pre-launch
Let’s open our editor. And if we go into our priv/repo directory there’s a file seeds.exs . Phoenix creates this for us as a way to populate our database with some dummy content.
Great our site looks a lot better – all our albums have been created.
Published May 14, 2018
$ mix run priv/repo/seeds.exs
Here we have a running Phoenix app that we downloaded, ran the migrations, and started the server. But as you can see, there’s not much going on. It would be a lot better if we could easily populate these fields with some data.
Great we see our album. But it looks a little lonely. Let’s go back to our seeds.exs And let’s update our script to create multiple albums.
Then we’ll go to the command line and run:
Let’s go back to the command line and run our seeds script again.
Let’s start by creating an alias for that module. Then we’ll call the create_album passing in the attributes we want.
In this episode we'll learn how to seed our Ecto database with some dummy info for use in a Phoenix application.