Quantcast
Channel: Active questions tagged ruby - Stack Overflow
Viewing all articles
Browse latest Browse all 4610

Optimize query in Rails

$
0
0

I have the following code:

results = Report.where(:car => 'xxxx').group(:date, :name, :car).select('date, name ,car, info, MAX(price) AS max_price')for customer in customers  result = results.where(:date => customer.date, :name => customer.name, :car => customer.car).first .... rest of the code ....end

I have a database with many records ~20,000, so I want to optimize the code and cache results in memory.Once again: my overall intention is make this code more efficient in terms of time. I want it to run faster than it is now and I want to reduce amount of database calls.

I am thinking of making my inital results object an array. I have a remote database so each .where query takes sometime. When I make results an array by adding .to_a - I load it to memory. So I think, it should be better(but not really sure)

Something like:

results = Report.where(:car => 'xxxx').group(:date, :name, :car)                .select('date, name ,car, info, MAX(price) AS max_price')                .to_afor customer in customers result = results.select {|result| result.date == customer.date and result.name == customer.name and result.car == customer.car }                 .firstend

Viewing all articles
Browse latest Browse all 4610

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>