[英]How can do a performance friendly version of this Ruby code?
大家好,我是 RoR 和 ruby 的新手。
在这个项目中,我目前正在展示 4 张以前由用户上传的车辆图像。
在我的类“Vehicle”中,我有一个单例方法- 返回一个带有车辆对象附加图像的 url 的数组 -我称之为Vehicle.vehicle_images(@vehicle.id)
。 我想让这个方法看起来更高效,更少硬编码。
我的车辆等级:
class Vehicle < ApplicationRecord
has_many :vehicles_attachment, dependent: :destroy
has_many :vehicles_attachment_imagem, -> { where({ type_attachment: 'imagem' }) }, class_name: 'VehiclesAttachment', dependent: :destroy
def self.vehicle_images(vehicle_id)
if vehicle_id
images = VehiclesAttachment.where({ vehicle_id: vehicle_id, type_attachment: :imagem })
urls = []
if !images.nil? && !images.empty?
count = 0
images.each do |img|
urls << if img.attachment.file?
"https:#{img.attachment.url(:regular)}"
else
4.times do
urls << ActionController::Base.helpers.image_url('viatura.jpg', digest: false).to_s
end
end
count += 1
end
if count < 4
(4 - count).times do
urls << ActionController::Base.helpers.image_url('viatura.jpg', digest: false).to_s
end
end
else
4.times do
urls << ActionController::Base.helpers.image_url('viatura.jpg', digest: false).to_s
end
end
else
4.times do
urls << ActionController::Base.helpers.image_url('viatura.jpg', digest: false).to_s
end
end
urls
end
end
你能帮助我吗?
作为第一步,它可以简化为:
def self.vehicle_images(vehicle_id)
blank_image_url = ActionController::Base.helpers.image_url('viatura.jpg', digest: false).to_s
urls = []
if vehicle_id
VehiclesAttachment.where(vehicle_id: vehicle_id, type_attachment: :imagem).each do |image|
urls << img.attachment.file? ? "https:#{img.attachment.url(:regular)}" : blank_image_url
end
end
urls << blank_image_url while urls.size < 4
urls
end
但这只是第一步。 接下来的步骤可能是:
vehicle_id
。 如果不是,那么车辆上的实例方法将比类方法更好。 并且您将能够使用定义的关联而不是类上的where
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.