Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在时间戳范围内比较时间戳?_Ruby On Rails_Ruby_Timestamp_Date Range - Fatal编程技术网

Ruby on rails 在时间戳范围内比较时间戳?

Ruby on rails 在时间戳范围内比较时间戳?,ruby-on-rails,ruby,timestamp,date-range,Ruby On Rails,Ruby,Timestamp,Date Range,我目前在RubyOnRails数据库中有2个时间戳字段,定义如下: starttime:timestamp endtime:timestamp 我想在我的控制器中编写一个简单的函数,它将取当前时间,如果在开始时间和结束时间的范围内,则返回TRUE 我如何才能做到这一点?假设您有这些的模型设置,您可以这样做: def currently_in_range(model) now = DateTime.now model.starttime < now && now

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

starttime:timestamp
endtime:timestamp
我想在我的控制器中编写一个简单的函数,它将取当前时间,如果在开始时间和结束时间的范围内,则返回TRUE


我如何才能做到这一点?

假设您有这些的模型设置,您可以这样做:

def currently_in_range(model)
   now = DateTime.now
   model.starttime < now && now < model.endtime
end
def当前在def范围内(型号)
now=DateTime.now
model.starttime
不过,您可能应该把它放在模型的类中。比如:

class Thing < ActiveRecord::Base
   ...
   def current?
     now = DateTime.now
     starttime < now && now < endtime
   end
   ...
 end
class Thing
然后在控制器中,您可以调用
model.current?
对您的模型进行分类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
def激活? (starttime..endtime)==Time.now.to_i 结束 结束 类YourController您真的在使用时间戳而不是日期时间?您希望您的测试是包含的还是独占的?我会使用
def current?(now=DateTime.now)
来允许您通过不同的“now”进行测试或历史审核。否则你是对的。