2016-04-28 23 views
1

我想计算这样的未来日期:Rails的:使用存储在数据库中的“串”时间标识算算时间

Date.today + 1.year 
Date.today + 1.month 

要确定,如果未来日期必须一个month或一个year成未来我会从数据库请求durationduration值保存为一个字符串。

end_date = Date.today + 1.Duration.find(order.duration_id).duration 

我相信,上面的代码的执行过程如下:

Date.today + 1."year" #the quotes cause an error 

如何删除引号?

回答

2

在rails中,1.year的工作方式是:year1上的一个实例方法。在Ruby中,评估对象的任意方法,你只需要使用send('method_name')send(:method_name)

如果你有你的持续时间为一个字符串,你可以使用:send来评估实际持续时间:

duration = "year" 
1.send(duration) == 1.year 
+0

非常感谢为快速反应。有用! –