How do I seed data with a reference to a different resource?

I currently have a Blog context with a Post resource and a Comment resource. Comment has a reference to Post. When I’m seeding data in seeds.exs I want to always have the correct post id so that the comment actually belongs to a post. How do I go about doing that? Does Ecto have a function for this?

seeds.exs:

%{
  author: "José Valim",
  title: "Blog post #1",
  text: "This is a very interesting blog post"
}
|> Blog.create_post()

[
  %{
    text: "Good post",
    author: "John Doe"
  },
  %{
    text: "Love it!",
    author: "Ada Lovelace"
  }
]
|> Enum.each(fn comment ->
  Blog.create_comment(comment)
end)

Hey, don’t think it does.
What you are doing is fine.

What you could do is implement some sort of factory pattern to abstract some of that code. :slight_smile:

This is referencing testing, but the same pattern could be applied to seeding: Test factories — Ecto v3.10.1