我需要使用名为scope的rails找到与给定日期最近的日期。我需要在rails应用程序中找到最近的日期
与MySQL我可以使用DATEDIFF,但我想保持数据库不可知论,下列不使用SQLite工作:
named_scope :closest_to, lambda { |*args|
date = args.first
count = args[1] || 1
{:limit => count, :order => "ABS(DATEDIFF(hour, date_field, #{date.to_formatted_s :db}))"}
}
小心,这只适用于SQLite AFAIK。对于Postgresql,它会是这样的:ABS(#{date.to_s(:db)} - value)。更多信息在这里:http://www.postgresql.org/docs/7.3/static/functions-formatting.html – gamov 2011-12-12 08:47:24