Search code examples
elixirphoenix-frameworkecto

Preload all associations with an order_by


This is what I'm trying to do:

project =
      Repo.get!(Project, id)
      |> Repo.preload([rows: from(r in Row, order_by: r.index)] [images: from(i in Image, order_by: i.index)])

But I'm getting this error:

** (ArgumentError) the Access calls for keywords expect the key to be an atom, got: [images: #Ecto.Query<from i in Dreamhouse.Image, order_by: [asc: i.index]>]

Does anybody know what I'm doing wrong here?


Solution

  • The error message says, that you're trying to get an element from a keyword-list, but passing something unexpected instead of an atom.

    For example, the following code produces a similar error:

    keyword_list = [keyword: :argument]
    keyword_list[unexpected: :structure]
    

    So the problem is in this line:

    Repo.preload([rows: from(r in Row, order_by: r.index)] [images: from(i in Image, order_by: i.index)])
    

    You might want to provide one keyword list as an argument with all the associations you want to preload:

    Repo.preload([rows: from(r in Row, order_by: r.index), images: from(i in Image, order_by: i.index)])