Subscribe to access all episodes. View plans →

#47: Seeding Data in Phoenix

Published May 14, 2018

Elixir 1.6

Phoenix 1.3


In this episode we’ll cover how you can populate - or seed - your database with information.

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.

Luckily for us Phoenix provides an easy way for us to populate - or seed - our database with information.

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.

We see there are some instructions for how to run our seed file. Let’s update our file to create some albums. Our repo has an Albums context that we can use to create an album.

Let’s start by creating an alias for that module. Then we’ll call the create_album passing in the attributes we want.

priv/repo/seeds.exs

alias Teacher.Records
Records.create_album!(
  %{title: "Blonde on Blonde", artist: "Bob Dylan", year: "1966", summary: "Blonde on Blonde is the seventh ..."}
)

Then we’ll go to the command line and run:

$ mix run priv/repo/seeds.exs

It looks like our album was created - let’s start up our server and see what it looks like.

$ mix phx.server

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.

Let’s create a variable album_data that will hold a list of the album data we want to create. Our data will be a map of album data.

Then below let’s call Enum.each to enumerate over our albums, and for our function, we’ll pass in our album’s data calling Records.create_album!.

I’ll comment out where we inserted our first album so we don’t get a duplicate.

priv/repo/seeds.exs

alias Teacher.Records

album_data = [
  %{
    artist: "The Beatles",
    title: "Abbey Road",
    year: "1969",
    summary: "Abbey Road is the eleventh album ..."
  },
  %{
    artist: "Led Zeppelin",
    title: "Untitled",
    year: "1971",
    summary: "English rock band Led Zeppelin's ..."
  },
  %{
    artist: "Miles Davis",
    title: "Kind Of Blue",
    year: "1959",
    summary: "Kind of Blue is a studio album by American jazz trumpeter ..."
  }
]

Enum.each(album_data, fn(data) ->
  Records.create_album!(data)
end)
...

Let’s go back to the command line and run our seeds script again.

$ mix run priv/repo/seeds.exs

The we’ll start our server.

$ mix phx.server

And with our server running, let’s go back to the browser.

Great our site looks a lot better - all our albums have been created.

Phoenix provided a simple way for us to populate our database with some content.

© 2024 HEXMONSTER LLC