Minda Minda
Minda Minda

Reputation: 73

Rails as_json performance issues

I have an array of Active model records. The array will have at max about 75 objects in it. However the model is complicated with multiple associations and relationships. Right now I am overriding the as_json method to include only the necessary fields. This is taking about 13 seconds to load 60 objects. How can I speed this up? I have tried removing some of the more complicated queries such as get_vehichles with the assumption I could load that later but it does not seem to help performance significantly.

 def as_json
 hash = {}
 hash["title"] = calendar_title
 #hash["description"] = calendar_description
 hash["start"] = start_at.strftime("%Y-%m-%d")
 hash["end"] = end_at.strftime("%Y-%m-%d")
 hash["url"] = "/admin/appointments/#{id}"
 hash["base_amount"] = base_amount
 hash["start_at"] = start_at
 hash["end_at"] = end_at
 hash["tech_id"] = technician_id
 hash["asset_id"] = asset_id
 hash["customer_name"] = customer.full_name(false)
# hash["customer_id"] = customer_id
 hash["id"] = id
# hash["cust_addresses"] = customer.addresses
 hash["address"] = address
#   client_host = ClientHost::Location.find_by_id(address.client_host_locations_id)
# hash["customer_email"] = customer.email
# hash["customer_wholesale"] = customer.wholesale?
# hash["customer_tax_exempt"] = customer.tax_exempt?
# hash["vehicles"] = self.get_vehicles
end

def get_vehicles

vehicles = []
self.appointment_vehicles.each do |av|
  hash = {}
  hash["appointment_vehicle"] = av
  hash["total_amount"] = av.total_amount
  hash["vehicle"] = av.vehicle
  hash["package_display_title"] = av.package.display_title
  hash["package_amount"] = av.package.amount
  hash["upgrades"] = self.get_upgrades(av.upgrades)
  vehicles.push(hash)
end
return vehicles

end

Upvotes: 1

Views: 564

Answers (1)

Stuart
Stuart

Reputation: 1134

Not sure I'm getting you here but I'll give it a dig

require 'oj'
def get_vehicles
  vehicles = self.appointment_vehicles.map do |av|
    {
      appointment_vehicle: av,
      total_amount: av.total_amount,
      vehicle: av.vehicle,
      package_display_title: av.package.display_title,
      package_amount: av.package.amount,
      upgrades: self.get_upgrades(av.upgrades)
    }
  end

  vehicles
  # Oj.dump(vehicles) <-- if you need this hash as json
end

How's that?

Other than that, the activerecord query will be what's taking the most time. It'd be good if you can share the SQL query it executes when you retrieve your records?

Upvotes: 1

Related Questions