{"_id":"5777c96e5b2b430e00b982cb","category":{"_id":"5777c9635b2b430e00b982aa","version":"5777c9635b2b430e00b982a5","project":"54348ec95b10711400c6c445","__v":0,"sync":{"url":"","isSync":false},"reference":false,"createdAt":"2014-12-03T21:36:49.014Z","from_sync":false,"order":4,"slug":"bonus-guides","title":"Bonus Guides"},"project":"54348ec95b10711400c6c445","version":{"_id":"5777c9635b2b430e00b982a5","__v":1,"project":"54348ec95b10711400c6c445","createdAt":"2016-07-02T14:02:11.084Z","releaseDate":"2016-07-02T14:02:11.084Z","categories":["5777c9635b2b430e00b982a6","5777c9635b2b430e00b982a7","5777c9635b2b430e00b982a8","5777c9635b2b430e00b982a9","5777c9635b2b430e00b982aa"],"is_deprecated":false,"is_hidden":false,"is_beta":false,"is_stable":true,"codename":"","version_clean":"1.2.0","version":"1.2.0"},"__v":1,"user":"5435e00ad7d8700800bbec51","parentDoc":null,"updates":[],"next":{"pages":[],"description":""},"createdAt":"2016-06-14T14:30:58.297Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":13,"body":"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).\n\nFortunately, Phoenix already provides us with a convention for seeding data. By default Phoenix generates a script file for each app at `priv/repo/seeds.exs`, which we can use to populate our datastore.\n\nAlso 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](http://www.phoenixframework.org/docs/ecto-models) (if you haven't completed that Guide yet, you should do so before proceeding further).\n\nSo 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:\n\n```elixir\n  <%= application_module %>.Repo.insert!(%<%= application_module %>.SomeModel{})\n```\n\nFor 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:\n\n```elixir\n  ...\n  alias Linker.Repo\n  alias Linker.Link\n\n  Repo.insert! %Link{\n    title: \"Phoenix Framework\",\n    url: \"http://www.phoenixframework.org/\"\n  }\n\n  Repo.insert! %Link{\n    title: \"Elixir\",\n    url: \"http://elixir-lang.org/\"\n  }\n\n  Repo.insert! %Link{\n    title: \"Erlang\",\n    url: \"https://www.erlang.org/\"\n  }\n  ...\n```\n\nWith this script, we've set up some aliases and then progressed through a list of our Links which will each be written to the datastore when we run the `seeds.exs` file with mix run:\n\n```elixir\n  mix run priv/repo/seeds.exs\n```\n\nNote 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!`\n\nWe can also create a module to seed our data.\nThe reason this is sometimes advantageous is it allows us to quickly seed from IEx, and also keeps things modular.\nFor example:\n\n```elixir\ndefmodule <%= application_name %>.DatabaseSeeder do\n  alias <%= application_name %>.Repo\n  alias <%= application_name %>.Link\n\n  :::at:::titles_list [\"Erlang\", \"Elixir\", \"Phoenix Framework\"] // list of titles\n  @urls_list [\"http://www.erlang.org\", \"http://www.elixir-lang.org\", \"http://www.phoenixframework.org\"] // list of urls\n links\n\n  def insert_link do\n    Repo.insert! %Link{\n      title: (@titles_list |> Enum.take_random),\n      url: (@urls_list |> Enum.take_random)\n    }\n  end\n\n  def clear do\n    Repo.delete_all\n  end\nend\n\n(1..100) |> Enum.each(fn _ -> <%= application_name %>.DatabaseSeeder.insert_link end)\n```\n\nNow, we could add links trivially to our database in IEx like so:\n\n```elixir\n$ iex -S mix\niex(1)> <%= application_name %>.DatabaseSeeder.add_link\niex(2)> <%= application_name %>.Link |> <%= application_name %>.Repo.all\n#=> [%<%= application_name %>.Link{...}]\n```\n\nThis is nice for experimenting in IEx during development in many cases.\n\n#### Models are Initialized\n\nConveniently, 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.\n\nThis 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:\n\n```elixir\n  ** (Ecto.ConstraintError) constraint error when attempting to insert model:\n```\n\nWhich will be followed by a description of any constraint errors.\n\nIn the development environment, we can also modify our script to check for errors before executing the bang functions (e.g., checking for duplicates) to prevent them from failing.","excerpt":"","slug":"seeding-data","type":"basic","title":"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 testing purposes). Fortunately, Phoenix already provides us with a convention for seeding data. By default Phoenix generates a script file for each app at `priv/repo/seeds.exs`, which we can use to populate our datastore. 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](http://www.phoenixframework.org/docs/ecto-models) (if you haven't completed that Guide yet, you should do so before proceeding further). 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: ```elixir <%= application_module %>.Repo.insert!(%<%= application_module %>.SomeModel{}) ``` 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: ```elixir ... alias Linker.Repo alias Linker.Link Repo.insert! %Link{ title: "Phoenix Framework", url: "http://www.phoenixframework.org/" } Repo.insert! %Link{ title: "Elixir", url: "http://elixir-lang.org/" } Repo.insert! %Link{ title: "Erlang", url: "https://www.erlang.org/" } ... ``` With this script, we've set up some aliases and then progressed through a list of our Links which will each be written to the datastore when we run the `seeds.exs` file with mix run: ```elixir mix run priv/repo/seeds.exs ``` 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!` We can also create a module to seed our data. The reason this is sometimes advantageous is it allows us to quickly seed from IEx, and also keeps things modular. For example: ```elixir defmodule <%= application_name %>.DatabaseSeeder do alias <%= application_name %>.Repo alias <%= application_name %>.Link @titles_list ["Erlang", "Elixir", "Phoenix Framework"] // list of titles @urls_list ["http://www.erlang.org", "http://www.elixir-lang.org", "http://www.phoenixframework.org"] // list of urls links def insert_link do Repo.insert! %Link{ title: (@titles_list |> Enum.take_random), url: (@urls_list |> Enum.take_random) } end def clear do Repo.delete_all end end (1..100) |> Enum.each(fn _ -> <%= application_name %>.DatabaseSeeder.insert_link end) ``` Now, we could add links trivially to our database in IEx like so: ```elixir $ iex -S mix iex(1)> <%= application_name %>.DatabaseSeeder.add_link iex(2)> <%= application_name %>.Link |> <%= application_name %>.Repo.all #=> [%<%= application_name %>.Link{...}] ``` This is nice for experimenting in IEx during development in many cases. #### Models are Initialized 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. 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: ```elixir ** (Ecto.ConstraintError) constraint error when attempting to insert model: ``` Which will be followed by a description of any constraint errors. In the development environment, we can also modify our script to check for errors before executing the bang functions (e.g., checking for duplicates) to prevent them from failing.