Query select with dynamic key

I have a query:

    RetestCategory 
      |> select([rc], %{id: rc.id, name: rc.name})
      |> order_by([rc], rc.id)
      |> Repo.all      
      |> Enum.map(fn(rc) -> ["#{rc.name}": rc.id] end)
      |> List.flatten

But is there a way to avoid the Enum.map part by doing something like this?

    RetestCategory 
      |> select([rc], %{"#{rc.name}": rc.id})
      |> order_by([rc], rc.id)
      |> Repo.all      
      |> List.flatten
1 Like

I’m not sure you can get the to_string, but select([rc], {rc.name, rc.id}) should return you a keyword list.

1 Like

You do not want to dynamically create atoms as you do here. You should use the name as key in its original type.

@LostKobrakais version does already adhere to this advice.

3 Likes

Thanks @LostKobrakai and @NobbZ!