2016-08-05 53 views
0

我使用外生2.0,并试图运行此查询预紧协会:使用非默认belongs_to的原子

query = from e in EmpireInstance, 
     where: e.user_id == ^user.id, 
     preload: [: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 
+0

你可以添加'EmpireInstance'的模式吗? – Dogbert

+0

@Dogbert那里你去! –

+0

您确定错误消息是针对问题顶部的查询吗? (只是想确认。) – Dogbert

回答

1

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错误的方式?或者您以错误的方式在数据库中创建密钥。

如果不是,您可以发布您的迁移文件吗?

+0

啊我失踪了:我的has_xxx关联上的foreign_key!谢谢 –