Skip to main content
Source Link

Count associations in a Ruby model

I'm trying to figure out if there's a better way to run the code below. Basically Course is an association of Student and courses_needed is an array of Course where I have many Students have and need many Courses and I'm trying to figure out the demand. I've came up with the following code and it runs, which is fine, but when I want to display it on a statistics page with 36 Courses, the same code needs to be run once for each Course.

I've solved it now by having it run once a day, instead of real-time.

  def self.calculate_needed
    Course.all.each do |course|
      neededArray = Array.new
      needed = 0
      Student.all.each do |s|
        unless s.courses_needed.nil?
          s.courses_needed.each do |c|
            if c == course
              needed += 1
            end
          end
        end
      end
      course.needed = needed
      course.save
    end
  end