Seeding a user from terminal input

I am trying to seed a user. I know we can run seeds file by using the following command
mix run priv/repo/seeds.exs

But I would like to pass the following input attrs "first name"this, “last name”, “email” as user input from terminal - like “John”, “Doe”, “john.doe@gmail.com” to

{:ok, user} =
      MyApp.App.register_user%{
        attrs
      })

in seeds.exs.

Any suggestions on how to do this from terminal?

You can pass command-line arguments to the script:

mix run priv/repo/seeds.exs foo bar baz

and access them with with System.argv. You might find the OptionParser module useful.

3 Likes

@stefanchrobot Thank you. This helped. I have another question that I am currently stuck with. While seeding some of the data are repeated but I have unique_constraint on them. Is there any way to ignore this error and continue with seeding the db?

I’d strongly suggest separating one time setup from repeated tasks. I’d even argue the latter are not seeds to begin with.

Do you mind elaborating on time setup because my seeds file doesn’t have any time setup. Also if a data already exists, I want it to not create a duplicate, so skip, and proceed to next one.

“one time” as in “applied only once when a project is initially deployed/setup”

I understand this but in a case where I am manually seeding the db multiple times by running

mix run priv/repo/seeds.exs

how to handle this error or how to skip this error? I am new to Elixir so trying to understand things.

The file is just elixir code. You can make it not fail if things already exist (use upserts or check manually if things already exist). To me however seeds are a one time thing for creating a projects baseline db data. It’s not necessarily meant to be applied multiple times.

If you’re on PostgreSQL, you can do an upsert with INSERT INTO ... ON CONFLICT ... which is properly supported by Ecto. See the guide in docs.