Generic Paging Function

Ecto for Beginners : part 22 of 22 published on Sep 07, 2015

In the previous section we showed how we can use offset and limit to page through our Posts.

We can use that knowledge and make a function that will page through any query for any model.

# /web/queries/paging.ex
defmodule Readdit.Paging do
  import Ecto.Query
  
  def page(query), do: page(query, 1)
  
  def page(query, page), do: page(query, page, 10)

  def page(query, page, per_page) do
    offset = per_page * (page-1)

    query
    |> offset([_], ^offset)
    |> limit([_], ^per_page)
  end

end

Now we can use this function like (be sure to use alias to enable the shorthand notation):

# With Posts: second page, five per page
posts = Post |> Paging.page(2, 5) |> Repo.all

# With Tags: third page, 10 per page
tags = Tag |> Paging.page(3, 10) |> Repo.all