0

My model looks like this:

class Job < ActiveRecord::Base
  attr_accessor :start_time

  def start_time
    self.start_time = Time.now
  end

  def elapsed_time
    end_time = Time.now
    elapsed = end_time - self.start_time
  end

end

I want to measure the elapsed time, and self.start_time exists within the start_time method. However, in my elapsed_time method, self.start_time is nil. Why is that?

I am using rails 4.1.0 and ruby 2.0.0.

4

2 回答 2

1

您需要start_time使用初始化定义何时创建作业对象:

class Job < ActiveRecord::Base
  attr_accessor :start_time

  def initialize
    self.start_time = Time.now
  end

  def elapsed_time
    end_time = Time.now
    elapsed = end_time - self.start_time
  end

end

如果您不想start_time被绑定到作业初始化的时间,那么您需要创建一个实例变量来保存开始时间,并在调用elapsed_time方法时引用它:

class Job < ActiveRecord::Base
  attr_accessor :start_time

  def start_time
    @start_time = Time.now
  end

  def elapsed_time
    end_time = Time.now
    elapsed = end_time - @start_time
  end

end
于 2014-04-15T05:08:11.527 回答
0

Beartech的答案是正确的,但让我解释一下原因:

attr_accessor为您的模型创建settergetter方法。就像 db 属性的定义方式一样,它们创建了您在对象 ( @object.method) 上调用的方法,这意味着它们仅在创建对象时创建

您的问题是您依赖于attr_accessor在对象实例之间持久存在,这意味着数据不会在请求之间持久存在。如前所述beartech,解决此问题的方法是以某种方式将数据“存储”在start_time方法中,最好在初始化对象/类时完成

于 2014-04-15T06:35:28.173 回答