Last active
December 14, 2015 16:19
-
-
Save JustSilverman/5114515 to your computer and use it in GitHub Desktop.
Order by count of active record relations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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