shlogg · Early preview
Jetthoughts Dev @jetthoughts

Optimizing Database Queries With Ruby On Rails Facade Pattern

Here's where to put the logic for database queries optimization in Ruby on Rails: use the Facade pattern to move code to a separate class like FilmCarrier, making it easier to test and combine data from different tables.

Where to put the logic related to database queries optimization in a Ruby on Rails application. We want to answer this question by showing you the ‘Facade’ approach.



  
  
  Outline the problem

There is an application that stores a database of films and reviews. Every review has its own rate value.

class Film < ApplicationRecord
  has_many :reviews
end

    
    

    
    





class Review < ApplicationRecord
  belongs_to :film
end

    
    

    
    




We can calculate the average rate of each film,

class Film < ApplicationRecord
  has_many :reviews
  def avg_rating
    reviews.av...