shlogg · Early preview
Jetthoughts Dev @jetthoughts

Reducing N+1 Queries With SQL Views In Ruby On Rails

Reduce queries in Ruby on Rails: use SQL views with Scenic gem to precalculate average values, improving performance & convenience.

Consider the way to reduce the queries when calculating the average values and find the place where to do it in the Ruby on Rails application.


In the first part, we considered the solution with extracting logic to the separate class and implementing the Facade pattern. SQL views are another way for solving the N+1 problem when finding the average value in Ruby on Rails application.

  
  
  The Problem Setup

There is a Ruby on Rails application with models Film and Review. Every Review has its own rate value.


We can calculate the average rate of each film:

But when we need to show the av...