【问题标题】:How does rails active model serializer handle nested resource?Rails 活动模型序列化程序如何处理嵌套资源?
【发布时间】:2018-07-10 07:45:46
【问题描述】:

假设有两个表project和progress,一个project有很多progress(ont-to-many):

class Project < ApplicationRecord
  has_many :progresses
end

class Progress < ApplicationRecord
  belongs_to :project
end

我确实定义了 ProjectSerializer,如下所示:

class ProjectSerializer < ApplicationSerializer
  attributes :title, :state, :tags # and so on
  attribute :lateset_progress

  def lateset_progress
    object.progresses.order(created_at: :desc).first
  end
end

另外,我在控制器中初始化我的序列化器,如下所示:

def show
  project = Project.find(params[:id])
  resource = ActiveModelSerializers::SerializableResource.new(
               project, key_transform: :camel_lower, adapter: :json)
  render json: resource
end

问题是嵌套的 lastest_progress 没有被序列化器处理,并用下划线渲染所有属性。

真正的响应数据是:

{
    "project": {
        "id": 1,
        "title": "a test title",
        "tags": [
            "tag-A",
            "tag-B"
        ],
        "latestProgress": {
            "id": 45,
            "details": "run run run",
            "project_id": 1,
            "created_at": "2018-07-10 04:14:59 UTC",
            "updated_at": "2018-07-10 04:14:59 UTC"
        }
    }
}

【问题讨论】:

  • 你有什么错误吗?
  • @JagdeepSingh 已更新。
  • @Run 你到底想要什么回应?你不想要progresses 的所有属性吗?
  • @Gabbar 应该是驼峰式。

标签: ruby-on-rails active-model-serializers


【解决方案1】:

你可以这样使用:

class ProjectSerializer < ApplicationSerializer
     ...
     has_many :progresses, key: :lateset_progress do
         object.progresses.order(created_at: :desc).first
     end
     ...
end

如果您需要自定义序列化程序类,您可以使用其他选项。例如:has_many :progresses, key: :lateset_progress, serializer: CustomProgressSerializer do ...

关于 key_transform 的第二部分。我不确定如何使用ActiveModelSerializers::SerializableResource 实例进行渲染,但我在文档中看到了这些选项用于渲染方法rendering docs

的示例

我会推荐使用这种表示法

json_data = ActiveModelSerializers::SerializableResource.new(project,
    key_transform: :camel_lower, adapter: :json
).as_json

通过as_jsonfileds: [...] 选项,您可以管理属性列表,它的工作方式类似于“仅”。 例如as_json(fields: [:id, :updated_at])

但需要注意:如果你使用其他方式创建序列化器对象,args的顺序可以不同。

ProjectSerializer.new(project).as_json(nil, fields: [:id, :status])

对于 0.10.x 版本来说,一切都应该是事实

【讨论】:

  • 多么棒的第一个答案!
猜你喜欢
  • 1970-01-01
  • 2017-01-29
  • 2011-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
  • 2021-06-13
相关资源
最近更新 更多