有没有办法自动对使用 ActiveRecord::Base.store 存储的值进行类型转换?
举这个完全不切实际的例子:
class User < ActiveRecord::Base
store :settings, accessors: [ :age ]
end
user = User.new(age: '10')
user.age # => '10'
我知道我可以重写年龄的阅读器方法以将其转换为整数,但我很好奇是否有一种未记录的方法。
试图避免这种情况:
class User < ActiveRecord::Base
store :settings, accessors: [ :age ]
def age
settings[:age].to_i
end
end
user = User.new(age: '10')
user.age # => 10
更新
寻找类似的东西:
class User < ActiveRecord::Base
store :settings, accessors: {:age => :to_i}
end
或者:
class User < ActiveRecord::Base
store :settings, accessors: {:age => Integer}
end