【问题标题】:Rails as_json performance issuesRails as_json 性能问题
【发布时间】:2017-11-05 15:24:07
【问题描述】:

我有一组活动模型记录。该数组将最多包含大约 75 个对象。然而,该模型很复杂,具有多种关联和关系。现在我正在重写 as_json 方法以仅包含必要的字段。加载 60 个对象大约需要 13 秒。我怎样才能加快速度?我已经尝试删除一些更复杂的查询,例如 get_vehichles,并假设我可以稍后加载,但它似乎对性能没有显着帮助。

 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

结束

【问题讨论】:

  • 你能显示查询以从数据库中检索记录吗?

标签: ruby-on-rails json rails-activerecord


【解决方案1】:

不确定我会带你到这里,但我会试一试

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

怎么样?

除此之外,activerecord 查询将是最耗时的。如果您可以共享检索记录时执行的 SQL 查询会更好吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-22
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    相关资源
    最近更新 更多