我对使用 map 方法缺乏一些了解。
使用不带映射的 json 输出
format.json { render :json => @categories }
给我以下输出
[{"created_at":"2012-10-20T01:16:35+11:00","id":1,"name":"bathroom renovations","updated_at":"2012-10-20T01:16:35+11:00"}]
在映射中使用 json
format.json { render :json => @categories.map(&:name) }
给我这个输出
["bathroom renovations"]
我怎样才能让我的输出看起来像
[{"id":"1","name":"bathroom renovations"}]
最佳答案
我认为以下内容可能对您有用:
format.json {render json: @categories.map{|category| {:id => category.id, :name => category.name} }}
关于ruby-on-rails - 使用 map 方法格式化 JSON 输出 - Rails 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13190459/