如何在Ruby on Rails中正确序列化PostgreSQL列实现自动类型转换?
解决方案
有两种实用方法可以实现这个需求,不用每次手动调用to_i:
方法一:用ActiveRecord内置的serialize方法
直接在模型里指定列的序列化类型为Integer,Rails会自动用YAML处理序列化和反序列化:
class YourModel < ApplicationRecord serialize :target_column, Integer end
- 存储时:给该列赋值整数(比如
model.target_column = 123),数据库里会存成YAML格式的字符串(类似--- 123\n) - 读取时:直接拿到的就是整数类型,无需额外转换
方法二:自定义属性类型(更灵活,存储纯数字字符串)
如果不想存YAML格式,希望数据库里是纯数字字符串,可自定义属性类型:
- 创建类型文件
app/types/integer_string_type.rb:
class IntegerStringType < ActiveRecord::Type::Value # 读取数据库值时的转换逻辑 def cast(value) case value when String then value.match?(/^\d+$/) ? value.to_i : value # 仅纯数字字符串转整数,其他返回原内容 else value end end # 写入数据库时的转换逻辑 def serialize(value) value.to_s end end
- 在模型里使用这个自定义类型:
class YourModel < ApplicationRecord attribute :target_column, IntegerStringType.new end
- 存储时:赋值整数会转成纯数字字符串存在数据库(比如
123存为"123") - 读取时:自动转成整数,若列中是非数字字符串则返回原内容
内容的提问来源于stack exchange,提问作者bcan001
相关产品推荐
相关产品推荐

