Sergio Tapia
Sergio Tapia

Reputation: 9823

Custom sort by direction and column name in Ecto

In the first line I'm setting the order_by clause by hard coding the direction and column name.

order_by = [desc: :inserted_at]
results =
  from t in Transmission,
  where: ilike(t.name, ^"%#{params["term"]}%"),
  order_by: ^order_by

How can I set these dynamically? The UX is a user clicking on a table column header and changing the sort order of that particular field.

Couldn't find anything in the documentation: https://hexdocs.pm/ecto/Ecto.Query.html#order_by/3

Imagine I have these two variables from the params object in my controller:

sort = "asc"
field_name = "inserted_at"

Upvotes: 0

Views: 844

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 120990

sort = "asc"
field_name = "inserted_at"

order_by = [{String.to_atom(sort), String.to_atom(field_name)}]

or

order_by = [{:"#{sort}", :"#{field_name}"}]

or even

[[sort, field_name]
 |> Enum.map(&String.to_atom/1)
 |> List.to_tuple]
#⇒ [asc: :inserted_at]

Under the hood, the keyword is a list of tuples, each having two elements.

iex(1)> [a: 42] == [{:a, 42}]
true

Upvotes: 4

Related Questions