Skip to content

Instantly share code, notes, and snippets.

@jfgomez86
Created July 29, 2011 16:10
Show Gist options
  • Save jfgomez86/1114133 to your computer and use it in GitHub Desktop.
Save jfgomez86/1114133 to your computer and use it in GitHub Desktop.
Finding latest tweets by unique users
##
# Find latest *n* tweets, but don't repeat tweets by users.
# Example:
#
# If we have the following table:
#
# id | user_id | created_at
# 1 | 1 | 3 days ago
# 2 | 2 | 3 days ago
# 3 | 1 | 2 days ago
# 4 | 1 | 2 days ago
# 5 | 3 | 1 day ago
# 6 | 2 | 1 day ago
#
# Then this would return something like this:
#
# id | user_id | created_at
# 6 | 2 | 1 day ago
# 5 | 3 | 1 day ago
# 4 | 1 | 2 days ago
#
#
# Limitations: This assumes that the greater id, the greater the date on the
# created_at field
class Tweet < ActiveRecord::Base
scope :recent, lambda {|limit|
where(id: select("max(tweets.id)").group("tweets.user_id").arel)
.order("tweets.created_at DESC")
.limit(limit)
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment