Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.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 使用两列getter扩展ActiveRecord::Base_Ruby_Activerecord_Ruby On Rails 3.2 - Fatal编程技术网

Ruby 使用两列getter扩展ActiveRecord::Base

Ruby 使用两列getter扩展ActiveRecord::Base,ruby,activerecord,ruby-on-rails-3.2,Ruby,Activerecord,Ruby On Rails 3.2,我正在使用一个遗留数据库模式,该模式定义了Rails“创建时”和“更新时”的等价物: 数据库中几乎所有20个左右的表都有这些列,我已经为其编写了getter代码 def createDate DateTime.strptime(read_attribute(:createDate), "%s") end def modifiedDate DateTime.strptime(read_attribute(:createDate), "%s") end 如何“扩展

我正在使用一个遗留数据库模式,该模式定义了Rails“创建时”和“更新时”的等价物:

数据库中几乎所有20个左右的表都有这些列,我已经为其编写了getter代码

  def createDate
    DateTime.strptime(read_attribute(:createDate), "%s")
  end

  def modifiedDate
    DateTime.strptime(read_attribute(:createDate), "%s")
  end

如何“扩展”ActiveRecord::Base以使我的所有模型都获得这两种方法?

您可以创建一个模块并将其包含在ActiveRecord::Base中:

module LegacyTimestamps
  def createDate
    DateTime.strptime(read_attribute(:createDate), "%s")
  end

  def modifiedDate
    DateTime.strptime(read_attribute(:modifiedDate), "%s")
  end      
end

ActiveRecord::Base.send :include, LegacyTimestamps
也可以仅在某些型号中包含此类模块:

class User < ActiveRecord::Base
  include LegacyTimestamps
end
class用户
谢谢。你建议我把这个放在哪个文件里?我的第一个猜测是初始值设定项。实际上这引发了一个错误:createDate是由ActiveRecord定义的(ActiveRecord::DangerousAttributeError)。。想法?你正在运行什么版本的rails?3.2。我现在将它转换为一个类LegacyTimestampclass User < ActiveRecord::Base include LegacyTimestamps end