Skip to content

Instantly share code, notes, and snippets.

Created January 8, 2013 18:17
Show Gist options
  • Save anonymous/4486400 to your computer and use it in GitHub Desktop.
Save anonymous/4486400 to your computer and use it in GitHub Desktop.
class EntriesController < ApplicationController
ITEMS_PER_PAGE = 50
def index
subreddit = params[:subreddit].to_i
subreddit = Subreddit.find_by_id(subreddit)
where_filter = {}
if subreddit
where_filter = {
subreddit_id: subreddit.id
}
end
pages, extra = Entry.where(where_filter).count.divmod(ITEMS_PER_PAGE)
pages += 1 if extra > 0
page = params[:page].to_i
page = page < 1 ? 1 : page
skip = (page - 1) * ITEMS_PER_PAGE
data = Entry.where(where_filter).limit(ITEMS_PER_PAGE).offset(skip).order("id DESC")
next_page = page < pages ? page + 1 : page
prev_page = page > 1 ? page - 1 : page
next_page = "/entries/?page=#{next_page}"
prev_page = "/entries/?page=#{prev_page}"
render json: {page: page, next: next_page, prev: prev_page, data: data}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment