【发布时间】:2015-09-15 21:30:28
【问题描述】:
我有一个 ActiveModel::Serializer 问题要请教专家。假设我有以下 JSON 输出,其中根元素是 SurveyInvite 对象。目前question_answers 哈希键只是QuestionAnswer 对象的数组。我怎样才能使question_answers 是QuestionAnswer 对象的哈希,其中键是QuestionAnswer.question.id?
{
id: 1,
email: "foo@example.com",
status: "Submitted",
created_at: "10:57AM Sep 1, 2015",
date_submitted: "10:58AM Sep 1, 2015",
survey_response: {
id: 1,
survey_invite_id: 1,
name: "Foo Bar",
title: "Ninja",
published: true,
created_at: "10:58AM Sep 1, 2015",
updated_at: " 3:42PM Sep 2, 2015",
question_answers: [
{
id: 1,
survey_response_id: 1,
mini_post_question_id: 20,
answer: "What is the answer?",
created_at: "2015-09-14T14:59:39.599Z",
updated_at: "2015-09-14T14:59:39.599Z"
},
{
id: 2,
survey_response_id: 1,
mini_post_question_id: 27,
answer: "What is the answer?",
created_at: "2015-09-15T20:58:32.030Z",
updated_at: "2015-09-15T20:58:32.030Z"
}
]
}
}
这是我的 SurveyResponseSerializer:
class SurveyResponseSerializer < ActiveModel::Serializer
attributes :id, :survey_invite_id, :name, :title, :published, :created_at, :updated_at
has_many :question_answers
def created_at
object.created_at.in_time_zone("Eastern Time (US & Canada)").strftime("%l:%M%p %b %w, %Y")
end
def updated_at
object.updated_at.in_time_zone("Eastern Time (US & Canada)").strftime("%l:%M%p %b %w, %Y")
end
end
基本上,我希望 question_answers 键值是 QuestionAnswer 对象的哈希,其中键是问题 ID QuestionAnswer.question_id。我浏览了文档,但没有找到任何我正在尝试做的事情的例子。
更新解决方案:
所以我想出了一个可以满足我需要的解决方案,但我仍然想知道是否有更好的方法来满足我的需要。我写了一个方法来生成我需要的结构。
def question_answers
hash = {}
object.question_answers.each do |answer|
hash[answer.mini_post_question_id] = answer
end
hash
end
产生以下结果:
question_answers: {
20: {
id: 1,
survey_response_id: 1,
mini_post_question_id: 20,
answer: "Test?",
created_at: "2015-09-14T14:59:39.599Z",
updated_at: "2015-09-14T14:59:39.599Z"
},
27: {
id: 2,
survey_response_id: 1,
mini_post_question_id: 27,
answer: "Blarg!",
created_at: "2015-09-15T20:58:32.030Z",
updated_at: "2015-09-15T20:58:32.030Z"
}
}
【问题讨论】:
标签: ruby-on-rails json active-model-serializers