Skip to content

Instantly share code, notes, and snippets.

@JustSilverman
Last active December 14, 2015 16:19
Show Gist options
  • Save JustSilverman/5114515 to your computer and use it in GitHub Desktop.
Save JustSilverman/5114515 to your computer and use it in GitHub Desktop.
Order by count of active record relations
class Topic < ActiveRecord::Base
has_many :votes
# Something that provides the result of the method below,
# but without dominating the db
#SQL would look something like this
# SELECT topics.*, COUNT(id) as vote_count from topics
# join on votes where topic_id = topics.id
# group_by(topic_id)
# order by (vote_count)
def self.order_by_count
Topic.sort_by { |topic| 1.0 / topic.votes }
end
end
class Vote < ActiveRecord::Base
belongs_to :topic
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment