Ruby 使用两列getter扩展ActiveRecord::Base
我正在使用一个遗留数据库模式,该模式定义了Rails“创建时”和“更新时”的等价物: 数据库中几乎所有20个左右的表都有这些列,我已经为其编写了getter代码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 如何“扩展
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