我有一個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
}
json builder是DSL。一個人不應該將哈希傳遞給構建者,應該明確聲明一個DSL,比如'last_name @ profile.last_name'或其他什麼。 – mudasobwa
@mudasobwa如果我也有一個'show_tutor_profile.json.jbuilder'具有相同的鍵值對,幹什麼可以做到這一點? – Richard
我從來沒有用過建造者,因爲我沒有找到優雅的乾燥模式。可能唯一的辦法是有一個lambda,它在準備好的哈希上調用'public_send key,value'。順便說一句,'hash.to_json'有什麼問題? – mudasobwa