In ActiveRecord, how do I specify an attribute of a class that is evaluated only once throughout the page?

Let's say I have an ActiveRecord called Apples, and I want the class method to calculate the total value of each apple in my database like this:

def Apples.total_price
  Apples.sum(:price)
end

This is the method that I use in one of my views to create a pie chart. So, something like: Apples.brand ("red delicious"). Sum (: price) /Apples.total_price =% Pie Chart

Apples.brand ("fuji"). sum (: price) /Apples.total_price = another% pie chart

Apples.total_price is called repeatedly, but the value will not change at the moment. A) Does Rails repeat the request, or does it know to cache the value? And if he calls it repeatedly, then what is the way to define a method in Apple so that this total_price is only calculated once for the execution time of this view?

+3
source share
2 answers

As you defined it, I believe that this is done many times. Logs will be displayed accurately.

Using a method known as memoization, you only process it if necessary. Rails provides easy memoization like methods, but you are on your own for class methods.

This is how you roll your own memoization for a class method.

class Apple < ActiveRecord::Base
  cattr_reader :total_price

  def Apple.total_price
    @@total_price ||= Apples.sum(:price)
  end
end
+4

def total_price
  @total_price ||= calc_total_price
end

memoize.

def total_price
  #you long running code goes here
end
memoize :total_price

:

http://ryandaigle.com/articles/2008/7/16/what-s-new-in-edge-rails-memoization

+1

Source: https://habr.com/ru/post/1733036/


All Articles