Ecto: Ecto.Query.preload with module name is not working as expected

Created on 17 Oct 2017  Â·  7Comments  Â·  Source: elixir-ecto/ecto

Environment

  • Elixir version: Elixir 1.4.2
  • Database: PostgreSQL 9.6
  • Ecto version (mix deps): 2.1.4
  • Database adapter and version (mix deps): postgrex 0.13.2
  • Operating system: macOS 10.12.6

Current behavior

Code sample:

defmodule App.Story do
  use App.Web, :model

  alias App.{Card, Placement}

  schema "stories" do
    has_many :placements, Placement
    has_many :cards, through: [:placements, :card]

    timestamps()
  end
end

defmodule App.Placement do
  use App.Web, :model

  alias App.{Card, Story}

  schema "placements" do
    belongs_to :card, Card
    belongs_to :story, Story

    timestamps()
  end
end

defmodule App.Card do
  use App.Web, :model

  alias App.Placement

  schema "cards" do
    has_many :placements, Placement

    timestamps()
  end
end

query = from(s in App.Story)
cards_query = from(c in App.Card) # works
cards_query = App.Card # doesn't work
query = preload(query, cards: ^cards_query)

App.Repo.all(query)

in second case it trows an error: schema App.Card does not have association App.Card

Expected behavior

Expected (according to @ericmj) both cases to behave the same.

Bug Intermediate

Most helpful comment

Tackling this one as well!

All 7 comments

The preloader should call Ecto.Queryable.to_query/1 on all passed queryables instead of expecting them to already be %Ecto.Query{}.

@ericmj the issue is that we also allow it to be an atom which is the association name and we can't call Ecto.Queryable on that (at least not for atoms). I think our best option here is to improve the error message if the atom starts with "Elixir.". Thoughts?

Can we check if the atom is an association and then call the protocol?

This means a typo in the association name will now become a much worse error message, no?

We can still special handle the error message by checking Elixir. like you
suggested/

On Tue, Oct 17, 2017 at 8:17 PM, José Valim notifications@github.com
wrote:

This means a typo in the association name will now become a much worse
error message, no?

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/elixir-ecto/ecto/issues/2279#issuecomment-337321127,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AATV2hLDIf7BgYde4Fo3Z0YzRrrjU2Y9ks5stO9UgaJpZM4P8SdY
.

--
Eric Meadows-Jönsson

Tackling this one as well!

Fixed on master and backported to v2.2. For now just a better error message.

Was this page helpful?
0 / 5 - 0 ratings