2016-08-05 84 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!謝謝 –