ecto_mnesia icon indicating copy to clipboard operation
ecto_mnesia copied to clipboard

Preload fail because the foreign key is used, instead of the primary key

Open Awlexus opened this issue 5 years ago • 0 comments

I have the following schemas:

defmodule AnimeApi.Anime do
  use Ecto.Schema

  schema "animes" do
    field :title, :string
    field :url, :string
    has_many :themes, AnimeApi.Theme
  end
end

defmodule AnimeApi.Theme do
  use Ecto.Schema

  schema "themes" do
    field :title, :string
    field :type, :string
    belongs_to :anime, AnimeApi.Anime
    has_many :videos, AnimeApi.Video # Ignore this
  end
end

When I try to preload the themes of an Anime it fails:

iex(1)> alias AnimeApi.{Anime, Repo, Theme}
[AnimeApi.Anime, AnimeApi.Repo, AnimeApi.Theme]
iex(2)> Repo.get!(Anime, 1) |> Repo.preload(:themes)
** (FunctionClauseError) no function clause matching in EctoMnesia.Record.Ordering.sort/3

    The following arguments were given to EctoMnesia.Record.Ordering.sort/3:  

         # 1
        [
          %AnimeApi.Theme{
            __meta__: #Ecto.Schema.Metadata<:loaded, "themes">,
            anime: #Ecto.Association.NotLoaded<association :anime is not loaded>,
            anime_id: 1,
            id: 1,
            title: "ED \"Sayonara Solitaire\"",
            type: "ED",
            videos: #Ecto.Association.NotLoaded<association :videos is not loaded>
          },
          1
        ]

        # 2
        [
          %AnimeApi.Theme{
            __meta__: #Ecto.Schema.Metadata<:loaded, "themes">,
            anime: #Ecto.Association.NotLoaded<association :anime is not loaded>,
            anime_id: 1,
            id: 2,
            title: "OP \"Tsubasa wa Pleasure Line\"",
            type: "OP",
            videos: #Ecto.Association.NotLoaded<association :videos is not loaded>
          },
          1
        ]

        # 3
        [
          %Ecto.Query.QueryExpr{
            expr: [asc: {{:., [], [{:&, [], [0]}, :anime_id]}, [], []}],
            file: "/d/Programming/Elixir/anime_api/deps/ecto/lib/ecto/repo/preloader.ex",
            line: 165,
            params: nil
          }
        ]

    Attempted function clauses (showing 1 out of 1):

        defp sort([left], [right], ordering)

    (ecto_mnesia) lib/ecto_mnesia/record/ordering.ex:19: EctoMnesia.Record.Ordering.sort/3
    (stdlib) lists.erl:969: :lists.sort/2
    (ecto_mnesia) lib/ecto_mnesia/planner.ex:73: EctoMnesia.Planner.execute/6
    (ecto) lib/ecto/repo/queryable.ex:130: Ecto.Repo.Queryable.execute/5
    (ecto) lib/ecto/repo/queryable.ex:35: Ecto.Repo.Queryable.all/4
    (elixir) lib/enum.ex:1314: Enum."-map/2-lists^map/1-0-"/2

I think the error lies in the expression expr: [asc: {{:., [], [{:&, [], [0]}, :anime_id]}, [], []}], which should have use :id instead.

Sorry if this is the wrong place for posting this issue

Awlexus avatar Aug 20 '18 14:08 Awlexus