Skip to content

Instantly share code, notes, and snippets.

@ariejan
Created November 9, 2009 09:25
Show Gist options
  • Save ariejan/229832 to your computer and use it in GitHub Desktop.
Save ariejan/229832 to your computer and use it in GitHub Desktop.
class Feed
has_many :imports
# SQL:
# SELECT feeds.*, COUNT(imports.id) AS import_count
# FROM `feeds`
# LEFT OUTER JOIN imports ON imports.feed_id = feeds.id
# GROUP BY imports.feed_id
# ORDER BY import_count DESC
# LIMIT 5
#
# The SQL in MySQL gives me five (correct) results. Top feed has 16 imports.
#
# However, Feed.most_imported returns only 2 results. Top feed is correct, but has import_count "1" (string)
#
def self.most_imported(limit = 5)
find(:all,
:select => "feeds.*, COUNT(imports.id) AS import_count",
:joins => :imports,
:group => 'imports.feed_id',
:order => 'import_count DESC',
:limit => limit
)
end
end
class Import
belongs_to :feed
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment