【发布时间】:2016-07-26 05:19:14
【问题描述】:
我正在开发一个按小时计费的酒店预订应用程序。有一个peak_seasons 表存储start_date 和end_date。 Peak_Seasons 是我的应用程序中当前年份的预定义日期。每当客户在选定的时间进行预订时,我必须检查这些时间是否属于旺季,以便我可以为这些时间应用不同的费率。
这个操作太频繁了,我想优化一下。需要想法。我目前的伪代码是这样的:
def calculate_price(customer_start_time, customer_end_time)
price = 0
(customer_start_time.to_i...customer_end_time.to_i).step(1.hour) do |hour|
//now check if this hour belongs to peak season over here
if peak_seasons?(hour)
price += price + peak_season_price
else
price += price + standard_price
end
return price
end
//peak_seasons? somewhere
def peak_seasons?(hour)
PeakSeason.where("start_date <= ? and end_date >= ?", hour.to_date, hour.to_date).any?
end
当数百名客户检查选定时间的价格时,我猜这不是有效的代码,然后它将在选定的每个小时从数据库中获取数据。如何优化?
【问题讨论】:
-
是
customer_start_time, customer_end_timeDateTime? -
您可以使用
BETWEEN进行查询,? BETWEEN start_date AND end_date。您可以查询四个可能的区间交叉点,而不是每小时查询一次,最多 4 个查询。 -
@neydroid 是的,
customer_start_time, customer_end_time是日期时间。 @sschmeck,谢谢,是的,我可以通过检查间隔而不是小时来减少查询。有什么方法可以让我们只需要一次获取旺季并将其存储在内存中吗?会更好吗? -
其实客户只能选择从今天起3个月内的start_time和end_time。但是旺季是提前为全年预先定义的。那么我为什么不利用它,在 Rails 的一些内存中获取和存储旺季,并且只在需要时更新该内存。这样的事情可能吗?
标签: ruby-on-rails ruby database ruby-on-rails-4 rails-activerecord