【问题标题】:Serializing models to a json field in Rails using active_model_serializers使用 active_model_serializers 将模型序列化为 Rails 中的 json 字段
【发布时间】:2017-03-03 03:03:32
【问题描述】:

我有一个如下所示的任务模型:

class Task
   # has a title
   belongs_to :owner, class_name: "User"
   belongs_to :asignee, class_name: "User
end

还有一个带有 json 字段的 Sprint metadata:

create_table :sprints, id: :uuid do |t|
  t.json :metadata
end

class Sprint
    def close_sprint
        self.metadata = serialized_tasks
        self.save
    end
end

我正在使用活动模型序列化程序来序列化sprint tasks,如下所示:

def serialized_tasks
   ActiveModel::Serializer::CollectionSerializer.new(self.tasks, serializer: TaskSerializer).to_json
end

问题在于它将任务数据存储为 json string 而不是 json 对象。

序列化器如下所示:

class TaskSerializer < ActiveModel::Serializer
  attributes :title, :owner_name, :created_at, :status, :asignee_name, :asignee_email

  def owner_name
    object&.owner&.full_name
  end

  def asignee_name
    object&.asignee&.full_name
  end

  def asignee_email
    object&.asignee&.email
  end
end

如何使用 active_model_serializers 将有效的 JSON 对象存储在 rails json 字段中?如果不可能,如何查询关联数据作为有效的 JSON 对象存储在metadata 字段中?

【问题讨论】:

    标签: ruby-on-rails json serialization


    【解决方案1】:

    我能够使用 as_json 而不是 to_json 获得所需的哈希。

    as_json(options = nil)

    返回代表模型的哈希值。一些 配置可以通过options传递。

    选项 include_root_in_json 控制顶级行为 as_json。如果为真,as_json 将发出一个以 对象的类型。 include_root_in_json 选项的默认值为 假的。

    【讨论】:

      猜你喜欢
      • 2016-07-16
      • 2011-09-06
      • 2020-04-15
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      • 2023-04-06
      相关资源
      最近更新 更多