0

I am trying to cache some data from the database to reduce number of SQL queries to the database. Currently, what I am doing is that I will load a set of records from the database:

@records = Record.find(:all, :conditions => ["id < ?", 100])

and then iterate through this array to find the records that I really want:

@needed_records = Array.new
@records.each do |record|
  if record.is_needed
    @needed_records.push(record)
  end
end

So that whenever I need, i can just pass @records instead of actually accessing the database.

My question is, is there any shortcoming doing it this way? Is there any better way to do the equivalent?

Patrick
  • 17,669
  • 6
  • 70
  • 85
Edward
  • 1,914
  • 13
  • 26

1 Answers1

0

Two ways I'd recommend:

1) The better way would be to use conditions and scopes to filter the actual data you are looking for, instead of pulling and manually iterating over the records. This assumes you can translate "record.is_needed" into conditions or SQL to get desired results

2) Use Rails' Cache Store the store the results from the DB: http://guides.rubyonrails.org/caching_with_rails.html#activesupport-cache-store

Rails.cache.write(:records, @records)

Databases love to be queried... They get off on it!

omarvelous
  • 2,774
  • 14
  • 18