Use joins dynamically

I have to implement joins dynamically based on the incoming params. the param for join i am getting is like this"

 %{"join" => "right_join"}

so how can I use this to dynamically set the join in the query like this

right_join: a in assoc(q,  :customer)

I thought about converting right_join to atom :right_join and using it but its not working

Any suggestions?

Thanks

A solution could be to create a function which pattern matches the params by matching in the %{"join" => "right_join"} and takes a query. This way random params can’t break the query.

import Ecto.Query
def do_join(query, %{"join" => "right_join"}) do
   query
   |> join(:right_join, [q], assoc(q, :customer)
end
def do_join(query, _), do: query

The function returns a query which you can then send to a Repo.all or something similar.

TestApp.SomeSchema
|> do_join(params)
|> TestApp.Repo.all

The code is untested :smile:

1 Like