【发布时间】: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