2016-03-04 100 views
0

我有一個PORO TutorProfileHandler,它有一個函數json,它返回一個散列。在jbuilder中函數返回散列的散列數組

class TutorProfileHandler 

    def initialize(opts) 
     @profile = opts[:tutor_profile] 
    end 

    def json 
     tutor = @profile.tutor 
     return { 
      id: tutor.id, 
      first_name: tutor.first_name, 
      last_name: tutor.last_name.first + '.', 
      school: @profile.school, 
      avatar: @profile.avatar.url, 
      bio: @profile.bio, 
      academic_level: @profile.academic_level, 
      headline: @profile.headline, 
      major: @profile.major, 
      rate: @profile.rate, 
      rating: @profile.rating, 
      courses: JSON.parse(@profile.courses), 
      video_url: @profile.video_url 
     } 
    end 
end 

在我index_tutor_profiles.json.jbuilder,我想生成

{ 
    tutor_profile: [{id: 1, ...}, {id: 2, ...}, ...], 
    tutor_sum: 20 
} 

然而,當我做到這一點

json.tutor_profiles (@tutor_profiles) do |profile| 
    TutorProfileHandler.new({tutor_profile: profile}).json 
end 

json.tutor_sum @tutor_sum 

這讓我對tutor_profiles空數組。

但是,如果我將所有內容從TutorProfileHandler.json移動到jbuilder文件,它的工作原理。我如何明確地將TutorProfileHandler.json返回的散列值包含在jbuilder數組中?

注:這將返回一個數組,但它創建了一個新的鍵值對array:

json.tutor_profiles json.array(@tutor_profiles) do |profile| 
    TutorProfileHandler.new({tutor_profile: profile}).json 
end 

結果:

{ 
    array: [{id: 1, ...}, {id: 2, ...}, ...], 
    tutor_profile: [], 
    tutor_sum: 20 
} 
+0

json builder是DSL。一個人不應該將哈希傳遞給構建者,應該明確聲明一個DSL,比如'last_name @ profile.last_name'或其他什麼。 – mudasobwa

+0

@mudasobwa如果我也有一個'show_tutor_profile.json.jbuilder'具有相同的鍵值對,幹什麼可以做到這一點? – Richard

+0

我從來沒有用過建造者,因爲我沒有找到優雅的乾燥模式。可能唯一的辦法是有一個lambda,它在準備好的哈希上調用'public_send key,value'。順便說一句,'hash.to_json'有什麼問題? – mudasobwa

回答

0

有一個醜陋的做法:

json.tutor_profiles @tutor_profiles do |profile| 
    tmp_json = TutorProfileHandler.new({tutor_profile: profile}).json 
    json.(tmp_json, *(tmp_json.keys)) 
end 

我認爲最好的做法是直接在模型中嵌套。您可以從其github頁面獲得更多信息。

+0

它仍然返回一個空數組。 – Richard

+0

我編輯答案,希望有所幫助。 – Haozhao

+0

謝謝,但我只是決定完全跳過jbuilder並將邏輯粘貼到控制器中,從而在那裏呈現json散列。 – Richard