2011-05-24 81 views
1

以下是問題所在:我正在使用活動記錄並返回一些照片對象。這些照片對象的最終消費者將成爲移動應用程序。如何將關係中的屬性添加到呈現的JSON而不嵌套?

的反應需要有縮略圖形式返回移動開發者已經請求JSON回來這個樣子..

{ 
"root_url":'http://place.s3.amazonaws.com/folder/', 
"image_300":'image_300.jpg', 
"image_600":'image_600.jpg', 
"image_vga":'image_VGA.jpg', 
"image_full":'image.jpg' 
} 

,而不是像這樣:

{ 
"root_url":'http://place.s3.amazonaws.com/folder/', 
"thumbnails": { 
    "image_300":'image_300.jpg', 
    "image_600":'image_600.jpg', 
    "image_vga":'image_VGA.jpg', 
    "image_full":'image.jpg' 
} 
} 

至今的簡單方法是爲每個縮略圖創建列,並且它的工作原理。我不喜歡被鎖定,因爲如果我們以後需要不同的縮略圖,這意味着將數據添加到數據庫等。我寧願要麼只是在模型類中指定縮略圖,要麼有一個單獨的縮略圖表與一個表的每行的拇指。

我已經看過代表compos_of,在連接中使用GROUP_CONCAT ..在to_json中使用:method => ..這些看起來都不像選項。是否有捷徑可尋?

基本型號例如:

class Photo < ActiveRecord::Base 
    has_many :thumbnails, :as => :thumbs_for #polymorphic 
end 

class Thumbnail < ActiveRecord::Base 
    # columns = name, filename 
    belongs_to :thumb_for, :polymorphic => true 
end 

到目前爲止,結果看起來像這樣基於從傑西·賴斯的回答

def as_json(options) 
    options ||= {} #even if you provide a default, it ends up as nil 
    hash = super(options.merge({:include => :thumbnails})) 
    if thumbs = hash.delete(:thumbnails) 
    thumbs.each {|t| hash.merge!({t['name']=>t['filename']})} 
    end 
    hash 
end 

回答

10

可以非常簡單地使用自定義對象的JSON序列化as_json方法。

對於這一點,你可以這樣做:

def as_json(*args) 
    hash = super(*args) 
    hash.merge!(hash.delete("thumbnails")) 
end 

或者你可以做到這一點的超級手動

def as_json(*args) 
    hash = super() 
    thumbnails.each do |thumb| 
    # build thumbnail json 
    end 
end 

你不必依靠的ActiveRecord的超簡單的JSON序列化的方法。

+0

真棒,我會試試這個。 – radixhound 2011-05-24 20:53:25

相關問題