how can I paginate records not by N value quantity, but by created_at.day?

267 Views Asked by At

I have a table Post.

Columns: created_at, title, body

Default pagination behaviour is to show n items per page and than add link_to prev/next.

How can I paginate not by n items, but by created_on a date?

I've figured out the gem https://github.com/ankane/groupdate, but it only helps to group, not to do the pagination.

1

There are 1 best solutions below

2
Chris Heald On

In this case, it sound like you don't want pagination, you want query filtering based on a bucketed value. You will first need a distinct list of post days. You may need to use some database-specific query features to get that from timestamps. For example, with Postgres, you can use the date() function to extract just the date portion from your created_at timestamp, and we can get a distinct list of them:

dates = Post.pluck("distinct date(created_at)").sort

Note that this will induce a full table scan, so it'll be slow for a large number of posts.

How you use that list of dates is up to you. You might choose to render a list of them as links for the user to click, for example. You might then have your index method accept a date param, then use that to find posts on that date:

def index
  scope = Post.all
  if params[:date].present?
    date = DateTime.parse(params[:date])
    scope = scope.
      where("created_at >= ? AND created_at <= ?",
        date.beginning_of_day, date.end_of_day).
      order("created_at ASC")
  end

  # For the given date, paginate the posts on that date in pages of 25
  @posts = scope.page(1).per(25)
end