Use joins dynamically

Tags: #<Tag:0x00007f113ee2bca0>


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?



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
   |> join(:right_join, [q], assoc(q, :customer)
def do_join(query, _), do: query

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

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

The code is untested :smile: