Neil Neil - 3 months ago 9x
Ruby Question

Filters on ActiveRecord collection without firing off additional sql query

I make a query like so in order to return an ActiveRecord collection of objects:

@animals = Animal.all

Then elsewhere in my code I grab records from that collection:

#fires off additional sql query but I do not want it to
@specific_animals = @animals.where(animal_type: 'mammal')

#fires off additional sql query but I do not want it to
@specific_animals = @animals.where(animal_type: 'bird')

I only want the first statement of
to fire off an sql query. I would think that once you have the collection, there is no reason to query the database again for filters on that collection.

Question: How can I make it so that I can filter that ActiveRecord collection without making additional queries to the database?


ActiveRecord queries translate to SQL statements, which are only useful when sent to a database. But you can just use Ruby array methods to filter.

@specific_animals = { |a| a.animal_type == 'mammal' }

Note that you can no longer use this array with other ActiveRecord scopes or queries after using a Ruby array method, like select, reject, sort, etc.