在看到有關輸入轉換的評論之後,我想你可以重寫這些字段的getter和setter方法,如果你沒有以任何其他形式使用它們。也許沿着這些線會有所幫助。
重要的是要指出,這不僅會影響該字段的序列化。如果你想保持這些領域的正常行爲,我會按照塔德曼的建議去做。
# with_unix_time.rb
module WithUnixTime
# These methods lack error handling
def to_unix_time(*fields)
fields.each do |field|
# Override getter.
define_method field do
self[field].to_i
end
# Override setter
define_method "#{field}=" do |value|
self[field] = Time.at(value)
end
# Convenience method to retrieve the original DateTime type
define_method "raw_#{field}" do
self[field]
end
end
end
end
# chimichanga.rb
class Chimichanga < ActiveRecord::Base
extend WithUnixTime
to_unix_time :time_to_kill, :time_for_joke
end
這是所有'updated_at'字段或一堆其他無關的字段? – tadman
所有在其中都有日期的字段。目前,我有幾個不同型號的5。 作爲獎勵,輸入相反的東西。目前,我手動轉換每一個。 – TiggerToo
您可以繼承ActiveModel :: Serializer並引入您自己的'attributes'方法,它可以使用諸如':as_integer'之類的選項。 – tadman