预加载与非默认 belongs_to 原子的关联

Preload association with non-default belongs_to atom

我正在使用 Ecto 2.0 并尝试 运行 这个查询:

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

board 的架构如下所示:

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

  timestamps
end

EmpireInstance 架构:

schema "empire_instances" do
  ...

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

  timestamps
end

我收到此错误:

** (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}

看起来它仍在尝试使用 module_name + _id 的默认 belongs_to id。除了将 belongs_to 原子改回默认值之外,还有什么办法可以解决这个问题吗?

这是进行查询的代码:

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

来自 has_one/3 文档:

: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

因为current_schema是empire_instance,关键是empire_instance_id

也许您的 belongs_tohas_one 方向错了?或者您在数据库中以错误的方式创建了密钥。

如果没有,你能post你的迁移文件吗?