ActiveModel :: Serializer has_many对象的哈希值

时间:2015-09-15 21:30:28

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

我为专家提供了一个ActiveModel :: Serializer问题。假设我有以下JSON输出,其中根元素是question_answers对象。目前,QuestionAnswer哈希键只是question_answers个对象的数组。如何才能使QuestionAnswerQuestionAnswer.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" } ] } }

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

这是我的SurveyResponseSerializer:

question_answers

基本上,我希望QuestionAnswer键值是QuestionAnswer.question_id个对象的哈希,其中键是问号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"
    }
}

产生以下结果:

{{1}}

1 个答案:

答案 0 :(得分:3)

我不认为ActiveModelSerializers有一种惯用的方式来将has_many关联呈现为哈希,但是您可以使用单行代码来实现:

def question_answers
    object.question_answers.index_by(&:id)
end