Ruby on Rails - Active record loaded records scopes vs collection methods

Viewed 54

I have been working on a large scale rails application and have come across several cases related to performance working with scopes in active record.

For example, if i have two models Drawing and Shape,
Drawing has many Shapes -> has_many :shapes
and shapes have a scope

scope :squares, -> { where type: 'Square' }

Now, in a complex logic in drawing.rb where i have shapes already loaded, if i use scope like this in drawing.rb,
shapes.squares

active record again sends a query to Backend, but to prevent that, i need to make a separate method which filters loaded objects like this

def self.filter_squares(shapes)
   shapes.filter(&:is_square?)
end

but that makes code difficult to maintain, is there a way to merge scope and loaded objects collection method
0 Answers
Related