Search code examples
elixirecto

Dynamically selecting map Ecto


I have so far created the query:

query = from page in "wagtailcore_page",
      where: page.url_path == ^url_path,
      join: h in ^table_name,
      where: h.page_ptr_id == page.id

I now would like to dynamically select properties on h

For example if I pass in [:body, :footer] I would like to run:

query = from [_page, h] in query,
      select: %{body: h.body, footer: h.footer}

I found Ecto.Query.API.map which looks like it could be used in the solution to this problem.

But when I run:

from [_page, h] in query, select: EctoApi.map(h, [:body])

I get the error:

** (Ecto.Query.CompileError) `EctoApi.map(h, [:alphatext])` is not a valid query expression

According to the IMPORTANT message at the bottom of the map documentation we have to include the foreign keys used in the relationship when performing the join which we are not doing, but I don't know how to do this type of assoc for the type of dynamic join which we are doing


Solution

  • map can be used without importing anything. The actual function is implemented inside Ecto, Ecto.Query.API.map/2 is just for documentation purposes. The following should work:

    from [_page, h] in query, select: map(h, [:body, :footer])