我想在我的模型中定义一些虚拟属性,如下所示
class User
attribute :full_name, :string
attribute :mobile, :integer
serialize :properties
end
我想在用户表的属性列中以散列格式保存full_name
和mobile
。我怎么能这样做,请帮助。
如果您需要在properties
列中保存这两个属性,则必须首先确保properties
列是文本列。然后将以下内容添加到User
模型中。
serialize :properties, Hash
然后添加一个回调以确保正确构建属性:
before_save :serialize_properties
private
def serialize_properties
properties = { full_name: full_name, mobile: mobile }
end