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響應,然後在一個頁面的應用程序中使用。