Search code examples
ruby-on-railsrails-activerecordclass-method

Rails Iterate over collection in model's class method without reloading query?


I would like to iterate over a collection in a Model's class method. Unfortunately, the only way seems to be using all :

def self.do_something
  all.each do |question|
    #do stuff
  end
end

questions = Question.pick_random.load
User.all.each { |user| questions.do_something_for(user) }

The problem is : This load the questions every time the method is called... It's pretty slow, obviously. Is there any method to not reload the query ?


Solution

  • You could memoize the results:

    def self.do_something
      @do_something ||= begin
        all.each do |question|
          #do stuff
        end
      end
    end
    

    Then, the query (and the computation) will only be performed the first time you call the method. The next time, it will just return @do_something