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响应,然后在一个页面的应用程序中使用。