3

我的 RubyOnRails 数据库中目前有 2 个时间戳字段,定义为:

starttime:timestamp
endtime:timestamp

我想在我的控制器中编写一个简单的函数,如果它在 starttime 和 endtime 的范围内,它将获取当前时间并返回 TRUE 。

我怎么能做到这一点?

4

2 回答 2

4

假设您有这些模型设置,您可以执行以下操作:

def currently_in_range(model)
   now = DateTime.now
   model.starttime < now && now < model.endtime
end

不过,您可能应该将它放在模型的类中。就像是:

class Thing < ActiveRecord::Base
   ...
   def current?
     now = DateTime.now
     starttime < now && now < endtime
   end
   ...
 end

然后在你的控制器中你可以调用model.current?

于 2011-01-20T21:34:43.660 回答
1
class YourModel < ActiveRecord::Base
  def active?
    (starttime..endtime) === Time.now.to_i
  end
end

class YourController < ApplicationController
  def show
    @your_model = YourModel.first
    @your_model.active?
  end
end
于 2011-01-20T22:12:35.430 回答