0

I have a School and Result model where results belong to schools, and schools have results for every year. Each result has a field :score, and I am trying to rank each 'result' by its score but only for each year. So there will be different rankings for each different year.

1) What is the best way to achieve this ranking?

One approach I have thought of is to run a cron job every 10 minutes (for example) that updates the rank

update_rank.rake

task :build => :environment do
  Result.where(year: year).desc(:score).each_with_index do |result, position|
    result.update_attribute(:rank, position + 1)
  end
end

I have an issue here though:

2) How can I do the ranking for each different year? I could do something like below, but it seems a little bulky, is there anything else i could do?

task :build => :environment do

  eachyear = (1990..(Time.now.year)).to_a

  eachyear.each do |year|

    Result.where(year: year).desc(:score).each_with_index do |result, position|
      result.update_attribute(:rank, position + 1)
    end

  end

end
Jeremy Lynch
  • 6,780
  • 3
  • 52
  • 63

1 Answers1

0

If your wanting to update ranks every ten minutes, there is a great gem called Whenever that will handle the cron for you. https://github.com/javan/whenever

It may make sense create a Term or Year model that defines a specific timeframe. This would make your calculations easier and would also scale a bit nicer given schools typically have different schedules.

One gotcha is that you would need to make sure to generate a new term / year when the current one ends.

Example:

  class School
     has_many :terms
     has_many :results
  end


  class Term
    belongs_to :school
    has_many :results

    field :start_date
    field :end_date
  end

  class Result
     belongs_to :term
     belongs_to :school
  end

Obviously there is quite a bit more information you would need to consider... But hopefully that helps.

davissp14
  • 765
  • 4
  • 13