ruby - How to reduce number of queries in Rails -


i have cats table. cat has_many impressions, , impression has impression_count , impression_day columns - count aggregate of people who've viewed cat on given day.

what want create chart line chart showing number of impressions of cat on many dates. js charting library i'm using takes 2 arrays: chartvalues, , chartlabels.

my controller action generate arrays:

def show   @cat = cat.find(params[:id])    @from = @cat.created_at     @to = time.now    dates = (@from.to_date..@to)   @chartlabels = dates.to_a.map {|date| date.strftime("%b %e")}    shown = @cat.impressions.ordered.between(@from,@to)   @chartvalues = create_stats_for dates, shown end 

the private create_stats_for method used shovel 0 values array if no impressions recorded on date:

private  def create_stats_for dates, values     stat_values = []      dates.each |date|       valid_impression = values.find_by impression_day: date       if valid_impression         stat_values << valid_impression.impression_count       else         stat_values << 0       end     end      stat_values end 

the issue

my problem inefficient, can iterating on impressions several years worth of dates, resulting in incredibly slow page loads. there cases impression count can in hundreds.

i feel there's more efficient way achieve same goals, haven't figured out yet - perhaps loading impressions memory once, , iterating on those?

any give on appreciated.

edit: ordered , between methods (on impression model) requested in comments:

  def self.ordered     order('impression_day asc')   end    def self.between(from,to)     where("impression_day between ? , ?", from.to_date, to.to_date)   end 


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -