Tech
Ecto: How to build dynamic fragments and case statements
I needed a way to create a dynamic case statement for an order_by/3
call in a Phoenix app using Ecto.
Take the following example:
order_by_lowest_amount(queryable, rates) do
order_by(queryable, [x], fragment(
"""
CASE
WHEN ? = 'USD' THEN ? * ?
WHEN ? = 'AUD' THEN ? * ?
# ...
END ASC
""",
x.currency, x.amount, ^Map.get(rates, :USD, 1),
x.currency, x.amount, ^Map.get(rates, :AUD, 1),
# ...)
end