2015-09-15 76 views
2

我有專家的ActiveModel :: Serializer問題。比方說,我有以下JSON輸出,其中根元素是一個SurveyInvite對象。目前,question_answers散列鍵只是一個QuestionAnswer對象的數組。我怎樣才能讓question_answers是一個散列QuestionAnswer對象的鑰匙是QuestionAnswer.question.idActiveModel :: Serializer has_many哈希值對象

{ 
    id: 1, 
    email: "[email protected]", 
    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" 
    } 
} 

回答

2

我不認爲ActiveModelSerializers已呈現has_many協會作爲哈希的慣用方式,但你可以用一行代碼做到這一點:

def question_answers 
    object.question_answers.index_by(&:id) 
end 
相關問題