Rails范围内的DateTime.parse

时间:2012-09-23 10:22:18

标签: ruby ruby-on-rails-3

我正在尝试使用范围内的DateTime.parse将字符串转换为时间,但是我得到一个未定义的局部变量错误。

是否可以转换范围内的字段,还是需要尝试其他方法?

我的范围:

  scope :time_range, lambda {
    a = DateTime.parse(start_time_am)
    where("#{a} <= ?", Time.now.strftime('%H'))
  }  

- 更新 -

玩过这个,我发现我应该覆盖默认的访问者。我现在有以下内容:

  def start_time_am
    read_attribute(:start_time_am).strftime("%H%M").to_i
  end

在控制台中,我的start_time_am字段现在看起来像是:

 Promotion.last.start_time_am
  => 430 

但是,如果我想暂时定义一个新字段,那么我仍然可以使用初始字段。

我可以在控制台中访问它,但不能在搜索时访问它。例如

   def start_time_new
     read_attribute(:start_time_am).strftime("%H%M").to_i
   end

  def self.time_range
    time = Time.now.strftime('%H%M').to_i
    where("start_time_new <= ?", time)
  end

产生未知的列错误。我以为attr_reader会解决,但它不起作用。

由于

2 个答案:

答案 0 :(得分:1)

如果将其重写为等效的方法定义,那么可能更容易理解。

def self.time_range
  a = DateTime.parse(start_time_am)
  where("#{a} <= ?", Time.now.strftime('%H'))
end

start_time_am来自哪里?该方法没有任何参数。

答案 1 :(得分:0)

最后,我在where语句中进行了转换并删除了虚拟属性:

def self.time_available
  where("cast(start_time as time) <= cast(now() as time) and cast(end_time as time) >= cast(now() as time)")
end

希望能帮到某人