简体   繁体   English

Rails:使用存储在数据库中的时间标识符作为“字符串”来计算时间

[英]Rails: Calculate time using time identifier stored in database as “string”

I would like to calculate future dates like this: 我想像这样计算将来的日期:

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

To determine, if the future date needs to be one month or one year into the future I request the duration from a database. 为了确定将来的日期是将来的month还是year ,我从数据库中请求duration The duration value is saved as a string. duration值另存为字符串。

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

I believe that the above code executes as follows: 我相信上面的代码执行如下:

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

How do I remove the quotes? 如何删除引号?

In rails, the way 1.year works, is :year is an instance method on 1 . 在轨,路1.year的作品,是:year是一个实例方法1 In ruby, to evaluate an arbitrary method on an object, you just use send('method_name') or send(:method_name) 在ruby中,要评估对象上的任意方法,只需使用send('method_name')send(:method_name)

If you have your duration as a string, you can use :send to evaluate the actual duration: 如果您将持续时间作为字符串,则可以使用:send来评估实际持续时间:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM