2013-12-21 44 views
0

我正在使用Ruby和Sinatra發佈Web服務的項目。我遇到的問題是我無法弄清楚如何讓數組正確地序列化。我有兩條路線。控制數組的JSON序列化

get '/Post' do 
    postId= params[:id] 
    my_post = Post.new(BSON::ObjectId(postId)) 
    return my_post.to_json() #runs the to_json method in post 
end 

get '/SourcePosts' do 
    sourceId = params[:source] 
    my_source = Source.new(BSON::ObjectId(sourceId)) #returns an array of Posts 
    return my_source.get_posts.to_json() #ignores the to_json method in post 
end 

第一Post作品如我所料,打電話給我定製to_json其省略了延遲加載屬性的方法。第二個SourcePosts忽略我的覆蓋並轉儲所有內容,包括需要加載數據庫傾角的屬性。我的問題:如何讓ruby調用我的方法,或者在將數組序列化爲JSON時忽略昂貴的屬性?

+0

不知道我是否正確理解你的問題,但你不應該在代碼塊中使用'return'關鍵字,因爲它可能破壞'get'方法的邏輯。 – andrykonchin

回答

0

問題在於模型類中存在require 'active_support/all',這是干擾數組序列化的。