Search code examples
postgresqlelixirphoenix-framework

(Postgrex.Error) ERROR 42703 (undefined_column) column c0.users_id does not exist


My action failed with column c0.users_id does not exist hint: Perhaps you meant to reference the column "c0.user_id". I had checked but not sure what's wrong. here is my code below.

defmodule Test.Accounts.User do
  use Ecto.Schema
  import Ecto.Changeset
  alias Test.Accounts.Credential
  schema "users" do
    field :name, :string
    field :username, :string
    has_one :credential, Credential
    timestamps()
  end

defmodule Test.Accounts.Credential do
  use Ecto.Schema
  import Ecto.Changeset
  alias Test.Accounts.User
  schema "credentials" do
    field :email, :string
    field :user_id, :id
    belongs_to :users, User

    timestamps()
  end

My schema for both User and credential

defmodule Test.Repo.Migrations.CreateUsers do
  use Ecto.Migration

  def change do
    create table(:users) do
      add :name, :string
      add :username, :string

      timestamps()
    end

    create unique_index(:users, [:username])
  end
end


defmodule Test.Repo.Migrations.CreateCredentials do
  use Ecto.Migration

  def change do
    create table(:credentials) do
      add :email, :string
      add :user_id, references(:users, on_delete: :delete_all),
          null: false

      timestamps()
    end

    create unique_index(:credentials, [:email])
    create index(:credentials, [:user_id])
  end
end

Please can anyone point me in the right direction?


Solution

  • You have

    field :user_id, :id
    belongs_to :users, User
    

    in your Credenial definition. Either remove belongs_to or remove field :user_id and change belongs_to :users, User to belongs_to :user, User (singular).