I have a RoR app that hits the DB very often with individual queries. Problem is each query is taking like 100ms and some controller actions are taking too long to complete because of the amount of individual queries that ActiveRecord is generating.
Another problem is that I cannot use AR includes() (which would generate just one query) because I am having problems with AR-sqlserver-adapter and unicode strings ignoring indexes and I am removing unicode prefix from sql query by-hand (this is a long story...)
Example:
#model
class Company < ActiveRecord::Base
has_one: city
end
#controller
sql_string = where(:code => ['12B1', '34C8', '87DD', ...]).to_sql
sql_string = sql_string.gsub("N'","'") #remove unicode prefix
companies = find_by_sql(sql_string)
#companies = Company.where(:code => ['12B1', '34C8', '87DD', ...]).includes(:city) #I wish I could use this line
when I am accessing cities inside companies array, I see several individual queries for each city in the console, what slows down things a lot.
I would like to have 2 queries only: one for companies using SQL IN
and one for cities.
I have done that by hand (using virtual attributes), but, is there a "Rails way" of doing it ?
What I have done so far (caution, ugly code ahead):
def self.get_companies_by_code(code_array)
comps = Company.where(company_code: ['12B1', '34C8', '87DD', ...])
cities_id_array = comps.map {|c| c.city_id}.compact.uniq
cities = City.find(cities_id_array)
comps.each {|co|
co.virtual_city = cities.select{|ct| co.city_id==ct.id}.first }
comps
end