Skip to content

Instantly share code, notes, and snippets.

@javiercr
Created March 23, 2014 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javiercr/9722206 to your computer and use it in GitHub Desktop.
Save javiercr/9722206 to your computer and use it in GitHub Desktop.
Slow ActiveRecord query with custom SQL and will_paginate
@messages = Message.includes(:from_user, :to_user, :parent)
.where(
"messages.id IN (
SELECT MAX(id) FROM messages GROUP BY COALESCE(parent_id, id) ORDER BY id DESC
)"
).order("messages.id DESC").scoped
@messages = @messages.paginate(page: params[:page])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment