Preload associated record through embedded schema

Hi there!

I have a schema looking something like this:

defmodule Shop.Order do
  schema "orders" do
    embeds_many :lines, Line
  end
end
defmodule Shop.Line do
  embedded_schema do
    belongs_to :product, Product
  end
end

Now I’m trying to preload the products in the embedded Line-schema, but I get an error-message:

query = from(o in Order, limit: 1, preload: [lines: :product])
Repo.one(query)

# => schema Shop.Order does not have association :lines

That sort-of makes sense, I suppose, but is there a way around this?

3 Likes

Migrated away from embedded-schema’s to regular association with lines-table. Would still be interested to know if it’s possible to do it with embedded_schema though.

I just had the same problem and a search for the solution led me here.

I have wrote a quick Enum.reduce/3 implementation with caching using a map to solve it for myself.

I’m also interested to ask if there is a better solution and if there isn’t one maybe extending Ecto with one would be desirable?

Afaik belongs_to is now supported in ecto, even though it’s not backed by a foreign key constraint in the db.