【问题标题】:How to serialize virtual attributes in rails 5如何在rails 5中序列化虚拟属性
【发布时间】:2019-04-26 11:02:51
【问题描述】:

我想在我的模型中定义几个虚拟属性,如下所示

class User
  attribute :full_name, :string
  attribute :mobile,    :integer
  serialize :properties
end

我想将full_namemobile 以哈希格式保存在用户表的属性列中。我该怎么做,请帮忙。

【问题讨论】:

    标签: ruby-on-rails-4 ruby-on-rails-5 ruby-on-rails-5.2


    【解决方案1】:

    如果您需要将这两个属性保存在您的 properties 列中,您必须首先确保您的 properties 列是一个文本列。然后将以下内容添加到您的 User 模型中。

    serialize :properties, Hash

    然后添加回调以确保属性构建正确:

    before_save :serialize_properties
    
    private
    
    def serialize_properties
      properties = { full_name: full_name, mobile: mobile }
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      • 2015-02-04
      • 1970-01-01
      相关资源
      最近更新 更多