1
votes

I am getting crazy. Now working a half day on my problem and can't find the solution/error. Creating a chat, I got a chat model and a chat_user model which has a user model as a foreign key.

Chat has has_many :chat_users, Test.Chat.ChatUser, foreign_key: :chat_id as has many, and the chat_user has belongs_to :user, Test.User and belongs_to :chat, Test.Chat.Chat.

I am preloading the associations with:

  defp preload_associations(chat, params \\ nil) do
    Repo.preload(chat, [
     :chat_users
   ])
  end

The Error i get is: ** (Postgrex.Error) ERROR 42703 (undefined_column): column c0.user_id does not exist

The table chat_users in the database has the field user_id with a foreign key. It seems to me, Ecto is searching for user_id in chat instead of chat_user.

Any idea what I am doing wrong? Thanks.

EDIT: Models

defmodule Test.Chat.ChatItem do
@moduledoc false

use Test.Web, :model

schema "chats" do
  field :name, :string
  ...
  has_many :chat_users, Test.Chat.ChatUser, foreign_key: :chat_id
  timestamps()
end


defmodule Test.Chat.ChatUser do
use Test.Web, :model

schema "chat_users" do
  ...
  belongs_to :user, Test.User
  belongs_to :chat, Test.Chat.Chat
end

And

defmodule Test.User do
...
1
You better post your models here, it is easier to spot an error in models than in in-words description. - denis.peplin
Try to remove foreign_key: :chat_id from has_many definition. - denis.peplin
And... do you really want to preload chat_users, or you want to preload users instead? - denis.peplin
Removing foreign-key caused * (Ecto.QueryError) deps/ecto/lib/ecto/association.ex:495: field Test.Chat.ChatUser.chat_item_id in where does not exist in the schema in query. And yes. I want to preload chat_users, the next step is to preload users from chat_users. chat_users has fields I need and users also. REST-Api, need all the stuff at once in the response. - Sardoan

1 Answers

3
votes

Finally I found the error. Had nothing to do with my migration or the models. The problem was caused by some environment configurations. The script, which builds the dev and test database did not drop the test database, so it had no user_id in the chat_users table. The error occured with mix test inside the docker container, so finding the error was not easy. I am new to elixir and still hate the stacktrace, used to read some nice c# stacktrace ;) But thanks for the help.