Create dynamic bindings for where clause

After some clarifications on the #elixir-lang IRC channel from @josevalim it seems that @peerreynders suggestion was correct. Using named bindings can solve this problem!

So, if you have a query with proper named bindings you can pass them to your filter specification in order to be used when querying. Here’s a small snippet on how you can such dynamic filters:

  query =  from(w in whs_query, as: :withholding,
             join: b in Beneficiary, as: :beneficiary,
             on: [id: w.beneficiary_id])

  binding = :withholding
  field = :number
  value = "1"
​
  query |> where(
            [{^binding, t}],
            field(t, ^field) == ^value
          )

Thank you very much for helping with this !

6 Likes