在Rails3中,增加JSON格式数据输出非常方便,只需在Controller中稍作修改即可。一种做法是在controller的开始处添加respond_to :json,然后使用respond_with响应请求。举例:假定有模型:书(book),有两个字段:书名(name)和作者名(author),controller为BooksController,将其index方法修改为(假定在index方法中输出JSON数据):
class BooksController < ApplicationController // 支持html, xml ,json respond_to :html, :xml, :json def index @books = Books.all respond_with @books end // 其它方法忽略 ... end
此时启动服务后(执行rails s),访问地址:http://localhost:3000/books/index.json将返回类似以下格式的数据:
[ "book":{"id":1,"title": "BookA","author":"Author1"}, "book":{"id":2,"title": "BookB","author":"Author2"}, "book":{"id":3,"title": "BookC","author":"Author3"} ]
某些情况下我们需要改变JSON输出格式,比如:需要把数以万计的记录缓存到客户端的localStorage或local database,去掉数据类型名称book以及字段名称id,name,author,将大大减小数据尺寸。如何改变这种格式输出呢?比如,输出为以下的数组格式:
[ ["1","BookA","Author1"], ["2","BookB","Author2"], ["3","BookC","Author3"] ]
一行代码足矣。编辑文件app/views/books/index.json.erb,填入以下内容:
[<%= raw @books.map { |b| '["' + "#{b.id}" + '","' + "#{b.name}" + '","'"#{b.author}" + '"]' }.join(',') %>]
另一种有稍微改进的写法:
[<%= raw @books.map { |b| %{["#{b.id}","#{b.name}","#{b.value}"]} }.join(',') %>]
(结束)