0
votes

I'm using Ecto 2.0 and trying to run this query:

query = from e in EmpireInstance,
        where: e.user_id == ^user.id,
        preload: [:board]

the schema for board looks like this:

schema "board_instances" do  
  belongs_to :empire, PlexServer.EmpireInstance
  has_many :board_pieces, BoardTileInstance

  timestamps
end

EmpireInstance schema:

schema "empire_instances" do
  ...

  belongs_to :user, PlexServer.User
  has_one :board, PlexServer.BoardInstance
  ...

  timestamps
end

I'm getting this error:

** (Ecto.QueryError) deps/ecto/lib/ecto/association.ex:392: field PlexServer.BoardInstance.empire_instance_id in where does not exist in the schema in query:

from b in PlexServer.BoardInstance,
   where: b.empire_instance_id in ^[1],
   select: {b.empire_instance_id, b}

It looks like it's still trying to use the default belongs_to id of module_name + _id. Is there way to solve this, besides changing the belongs_to atom back to default?

Here's the code where the query is made:

def show(conn, _) do
  user = Guardian.Plug.current_resource(conn)

  query = from e in EmpireInstance,
        where: e.user_id == ^user.id,
        preload: [:board]

  case Repo.one(query) do
    nil -> 
      conn
      |> put_status(:unprocessable_entity)
      |> json(%{errors: ["No associated empire"]})
    empire ->  
      render(conn, PlexServer.EmpireInstanceView, "show.json", empire: empire)
  end
end
1
Can you please add the schema of EmpireInstance? - Dogbert
@Dogbert there ya go! - Alejandro Huerta
Are you sure that error message is for the query at the top of the question? (Just wanted to confirm.) - Dogbert
@Dogbert I added the code where I make the query. I'm 90% sure its coming from the query. - Alejandro Huerta
Thanks, looks good. I'm also confused why it's using empire_instance_id when belongs_to's documentation implies it should use association name + _id, so empire_id. What happens if you add , foreign_key: :empire_id after belongs_to :empire, PlexServer.EmpireInstance? - Dogbert

1 Answers

1
votes

From the has_one/3 docs:

:foreign_key - Sets the foreign key, this should map to a field on the other schema, defaults to the underscored name of the current schema suffixed by _id

Since the current_schema is empire_instance, the key is empire_instance_id

Perhaps you have your belongs_to and has_one the wrong way round? Or you created the keys in the database the wrong way round.

If not, could you post your migration files?