Ruby on rails 使用Rails在遗留数据库中隐藏unix时间戳
我正在使用遗留数据库编写RubyonRails应用程序。我遇到的问题是数据库中有一个unix时间戳列。我正在尝试这样做,这样我就可以编写一个字符串,如Ruby on rails 使用Rails在遗留数据库中隐藏unix时间戳,ruby-on-rails,timestamp,Ruby On Rails,Timestamp,我正在使用遗留数据库编写RubyonRails应用程序。我遇到的问题是数据库中有一个unix时间戳列。我正在尝试这样做,这样我就可以编写一个字符串,如“2010-10-10”,并在阅读时获得日期 def birthdate bdate = self[:birthdate] if bdate == 0 '' else if bdate =~ $CetConfig.regexp.date_format.regexp bdate else
“2010-10-10”
,并在阅读时获得日期
def birthdate
bdate = self[:birthdate]
if bdate == 0
''
else
if bdate =~ $CetConfig.regexp.date_format.regexp
bdate
else
Date.parse(Time.at(bdate).to_s)
end
end
end
def birthdate=(bdate)
self[:birthdate]= Time.parse(bdate.to_s).to_i
end
这些是我必须尝试的访问器,但是当数据由于错误或其他原因重新填充到表单中时,我会在文本字段中使用时间戳而不是日期字符串
这是表格。(element_块仅将元素和标签包装在dl的右侧标记中)
我使用的是Rails 2.3.5首先,当从数据库中获得零作为值时,不应返回空白字符串:
>> Time.at(0)
=> Thu Jan 01 01:00:00 +0100 1970
其次,您应该使用ActiveRecord提供的方法进行读/写操作:
def birthdate
Time.at(read_attribute(:birthdate)).to_date
end
def birthdate=(date)
write_attribute(:birthdate, date.to_time.to_i)
end
我最后做的是在模型中创建一个假字段作为日期,并使用after_验证过滤器将其转换为真实字段。 在模型中
after_validation :write_birthdate
def write_birthdate
bd = self.birthday
unless bd.nil?
write_attribute(:birthdate, Time.parse(bd).to_i)
end
end
...
def birthday
bd = read_attribute :birthday
if bd.nil?
bd = read_attribute :birthdate
return Date.parse(Time.at(bd).to_s).to_s unless bd.nil? or bd === 0
return nil
end
return bd
end
def birthday=(bdate)
write_attribute(:birthday, bdate)
end
alias :birthdate :birthday
alias :birthdate= :birthday=
通过这种方式,我将生日作为一个日期写入,但生日仍然是一个时间戳。我使用了read_属性和write_属性,但freenode上的RubyOnRails中有人说我不应该这样做。但是我觉得很愚蠢。我会在早上访问db.Nope时尝试这种变化。同样的结果。这就像FormHandler或其他填充表单的东西,没有使用访问器。你能将表单代码粘贴到原始问题中吗,我会让你知道发生了什么。另外,您使用的是什么版本的Rails?您使用的是自定义表单生成器/助手吗?你能把它也粘贴一下吗?谢谢
>> Time.at(0)
=> Thu Jan 01 01:00:00 +0100 1970
def birthdate
Time.at(read_attribute(:birthdate)).to_date
end
def birthdate=(date)
write_attribute(:birthdate, date.to_time.to_i)
end
after_validation :write_birthdate
def write_birthdate
bd = self.birthday
unless bd.nil?
write_attribute(:birthdate, Time.parse(bd).to_i)
end
end
...
def birthday
bd = read_attribute :birthday
if bd.nil?
bd = read_attribute :birthdate
return Date.parse(Time.at(bd).to_s).to_s unless bd.nil? or bd === 0
return nil
end
return bd
end
def birthday=(bdate)
write_attribute(:birthday, bdate)
end
alias :birthdate :birthday
alias :birthdate= :birthday=