horatius
horatius

Reputation: 814

What's the right way to seed a date field in phoenix framework?

I am creating a phoenix api app. Here's my code.

alias CardsWeb.Repo
alias CardsWeb.Infrastructure.User

Repo.insert! %User{login: "user", firstname: "User", lastname: "User", dateOfBirth: "1999-5-18"}

I get the following error when I run it

** (CompileError) priv/repo/seeds.exs:15: Infrastructure.User.__struct__/1 is undefined, cannot expand struct Infrastructure.User

Here's the entity definition.

defmodule Infrastructure.User do
  use Ecto.Schema
  import Ecto.Changeset

  schema "users" do
    field :dateOfBirth, :date
    field :firstName, :string
    field :lastName, :string
    field :login, :string

    timestamps()
  end

  @doc false
  def changeset(user, attrs) do
    user
    |> cast(attrs, [:login, :firstName, :lastName, :dateOfBirth])
    |> validate_required([:login, :firstName, :lastName, :dateOfBirth])
  end
end

Update: I noticed that firstname and lastname should be firstName and lastName. I corrected that, but I still get the same error.

Upvotes: 2

Views: 465

Answers (1)

Daniel
Daniel

Reputation: 2554

You cannot add date as string directly, instead of adding it as string use ~D sigil:

dateOfBirth: ~D[1999-05-18]

edit: The namespace you aliased in your seeds.exs for user schema is also incorrect, change:

alias CardsWeb.Infrastructure.User

to

alias Infrastructure.User

Upvotes: 2

Related Questions