2012-03-12 74 views
0

在軌道,可以說我這樣做:如何格式化從軌道控制器到JSON的結果?

def retrieveAllWidgets 
widgets = Widgets.all(:conditions => "status = 1") 

render :json => widgets 

end 

在軌控制。 json響應將包含暴露的小部件的所有屬性。問題是小部件有價格,並且在將JSON響應發送回客戶端之前,我希望將價格與number_with_currency進行格式化。

我想我能做到這一點:

def retrieveAllWidgets 
widgets = Widgets.all(:conditions => "status = 1") 

formattedWidgets = [] 
widgets.each do |widget| 
    formattedWidgets.push({"id" => widget.id, 
          ... 
          "price" => number_to_currency(widget.price) 
          } 
         ) 
end 

render :json => formattedWidgets 

end 

但就是這樣做呢?無論如何不用循環遍歷所有的結果而適當地格式化? number_to_currency真的很有用,但我認爲在視圖中最好使用,但這不適合作爲JSON響應的我的需要。我可能完全錯誤地做事。重點是它只是一個JSON響應,然後在一個頁面的應用程序中使用。

回答

0

據我所知,你必須格式化視圖中的數據RetrieveAllWidgets.json.erb。 你將不得不傳入@widgets。格式化後,視圖將返回json。 查找http://api.rubyonrails.org/查找erb可能有幫助