I'm having these models and following lines in a method where I am trying to improve performance of the code.
class Location < ActiveRecord::Base belongs_to :company end class Company < ActiveRecord::Base has_many :locations end In the method:
locations_company = [] ### found_locations = Location.within(distance, origin: from_result.split(',')).order("distance ASC") ### 0.002659s ### found_locations.each do |location| locations_company << location.company end ### 45.972285s ### companies = locations_company.uniq{|x| x.id} ### 0.033029s The code has this functionality - first, grab all locations within a specified radius. Then, from each found row take the company and save it to the prepared array. This is the problematic part - the each loop takes 45 seconds to process.
And then from this newly created array remove duplicities.
I still wondering if there would be a better approach to solve this situation, but I am afraid I don't see it right now, so I'd like to ask you guys how I could speed up the .each looping with saving data to the array - is there a better method in ruby to grab some information from an object?
Thank you very much for your time, I am immersed in this problem the whole day, but still don't have a more effective solution.
found_locationsyou'll notice that it's likely a query proxy, and not a coalesced result set. The#eachis almost certainly not your bottleneck; you should properly profile your code to find the bottlenecks.