Can't query table using Ecto

Hi. I’m building an app and I have “posts” model with associated “votes”.
My migration for the votes is:

defmodule DummyApi.Repo.Migrations.CreateVotes do
  use Ecto.Migration

  def change do
    create table(:votes) do
      add :book_id, references(:posts, on_delete: :delete_all)
      add :user_id, references(:users, on_delete: :delete_all)

      timestamps()
    end

    create unique_index(:votes, [:post_id, :user_id])
  end
end

And my votes schema is:

defmodule DummyApi.FeedBack.Vote do
  use Ecto.Schema
  import Ecto.Changeset
  alias DummyApi.Feedback.Post
  alias DummyApi.Accounts.User

  @required_fields [:post_id, :user_id]

  schema "votes" do
    field :post_id, :id
    field :user_id, :id
    belongs_to :users, User
    belongs_to :posts Post
    timestamps()
  end

  @doc false
  def changeset(vote, attrs) do
    vote
    |> cast(attrs, [])
    |> validate_required(@required_fields)
  end
end

When I try to get a vote record using the FeedBack context of my app I get this:

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

         query: SELECT v0."id", v0."post_id", v0."user_id", v0."users_id", v0."posts_id", v0."inserted_at", v0."updated_at" FROM "votes" AS v0 WHERE (v0."id" = $1)

         hint: Perhaps you meant to reference the column "v0.user_id".

belongs_to → singular :slight_smile:

has_many → plural

otherwise You mess up the keys… users_id instead of user_id

So it should be belongs_to :user

6 Likes

Its singular.

belongs_to :user, User
belongs_to :post Post
2 Likes