Nested preload queries : cannot encode to JSON

Hi guys!

I am trying to get nested datas with Ecto.query, but my code doesn’t work :

def myfunction(int_c_id, int_d) do
  a_query = from a in A, where: a.d == ^int_d
  b_query = from b in B, preload: [a: ^a_query]
  Repo.one from c in C, where: c.id == ^int_c_id, preload: [b: ^b_query]
end

The error message is “cannot encode association :a from Project.B to JSON because the association was not loaded”.

It’s not possible to proceed like that to get nested datas ?

Thanks!!

no one? :confused:

At least for me, Ecto questions are pretty hard to approach if there is just a small pseudo-example offered without a glaringly obvious problem on display … it may help if you could provide a minimal example that could be run locally …

When I check the content of result request, the association in question is loaded…

[%Mygame.B{__meta__: #Ecto.Schema.Metadata<:loaded, "bs">, a: [%Mygame.A{__meta__: #Ecto.Schema.Metadata<:loaded, "as">,   inserted_at: #Ecto.DateTime<2017-07-11 09:17:54> id: 715, inserted_at: #Ecto.DateTime<2017-07-11 09:17:54> [...]

I use Poison.Encoder in my models, like that :

@derive {Poison.Encoder, only: [:id, :var_a, :var_b, :var_c, :a]}
schema "bs" do

  field :var_a, :integer
  field :var_b, :integer
  field :var_c, :integer

  has_many :a, Project.A
end

I don’t understand why Poison.Encoder can’t encode the association…

Well this implies it is trying to serializing a field that is not loaded, whether that is :a or something inside :a.

As I said earlier, that field seems loaded when I check the content of result request… :confused:

[…] a: [%Mygame.A{meta: #Ecto.Schema.Metadata<:loaded, “as” […]>

cannot encode association :a from Mygame.B

Maybe i can’t use nested queries with preload parameters

I don’t think so (though I’m not sure, I don’t use preloads 99% of the time), you have to put all preloads at the top level (you can preload nested from the top level though).

Ok no sorry, this code doesn’t work too :

Repo.all from b in B, preload: [:a]

It’s really weird, because i have an identical schema struct in my project, but which works.

EDIT: Sorry it’s an inattention mistake… My bad, thank guys.

1 Like