Ecto Sort v0.0.1 Ecto.Sort View Source

Ecto.Sort is a simple module which provides a macro for explicitly applying ecto order_by expressions.

Example

defmodule Post do
  use Ecto.Schema

  schema "post" do
    field(:name, :string)
    field(:featured, :boolean)
    has_many(:comments, Comment)
    timestamps()
  end
end

defmodule Comment do
  use Ecto.Schema

  schema "comment" do
    field(:body, :string)
    timestamps()
  end
end

defmodule Posts do
  import Ecto.Query, warn: false
  use Ecto.Sort

  add_sort(:inserted_at)
  add_sort([:name, :featured])
  add_sort(:comments_inserted_at, fn direction, query ->
    query
    |> join(:left, [p], c in assoc(p, :comments), as: :comments)
    |> order_by([comments: comments], [{^direction, comments.inserted_at}])
  end)

  defp query(params \ %{}) do
    apply_sorting(Post, params)
  end

  def list_posts(params \ %{}), do: Repo.all(query_posts(params))
  def get_post(params \ %{}), do: Repo.one(query_posts(params))
end

Link to this section Summary

Link to this section Functions

Link to this macro

add_sort(key, fun) View Source (macro)