yarism
yarism

Reputation: 465

Sort a list based on number of votes

I am trying to create a new list of a old list that contains all the "Stories" of my site.

Every story contains of several chapters which has a number of votes on them. I want a new list with all stories sorted after the amount of votes.

This is my code so far:

def mostVoted
    allStories = Story.all
    allStories.each do |story|
        votes = 0
        story.chapters.each do |chapter|
            votes = votes + chapter.votes.count
        end
    end
end

Could someone please help me get further? Thanks!

Upvotes: 1

Views: 560

Answers (3)

engineersmnky
engineersmnky

Reputation: 29393

Why not use a query such as

Story.joins(:chapters).order("count(chapters.votes)").select("stories.name").group("stories.name")

This will help eliminate n + 1 queries associated with the above answers. Not sure what data you are trying to get with this so I took a few liberties.

Upvotes: 2

Kyle Decot
Kyle Decot

Reputation: 20815

def mostVoted
  Story.all.sort_by do |story|
    story.chapters.map do |chapter| 
      chapter.votes.count
    end.reduce(0, :+)
  end
end

Upvotes: 1

sawa
sawa

Reputation: 168139

def mostVoted
  Story.all
  .sort_by{|story| story.chapters.inject(0){|n, chapter| n + chapter.votes.count}}
end

Upvotes: -1

Related Questions