我使用rails 2.3.8
def index
@posts = Post.all
respond_to do |format|
format.html # index.html.erb
format.json { render :json => ({ :results => @posts.size, :rows => @posts.to_json(:only => [:id, :title, :click_count, :body])}).to_json }
end
end
生成的json数据是:
{ “行”: “ [{\” 标题\ “:\” 红宝石\”,\ “身体\”:\ “goood \”,\ “click_count \”:1, \ “ID \”:1},{\ “标题\”:\ “G \”,\ “身体\”:\ “H \”,\ “click_count \”:1,\ “ID \”:2} ]的 “下,” 结果“:2}
但实际上是shuld:
{ “行”:[{\ “标题\”:\ “红宝石\”,\ “身体\”:\ “goood \”,\ “click_count \”:1,\ “ID \”:1} {\ “标题\”:\ “G \”,\ “身体\”:\ “H \”,\ “click_count \”:1,\ “ID \”:2}], “结果”:2}
这是rails中的错误吗?
现在怎样才能为我生成预期的json数据?
谢谢!
答案 0 :(得分:1)
抱歉,这是我的错。
动作代码应为
def index
@posts = Post.all
respond_to do |format|
format.html # index.html.erb
format.json { render :json => ({ :results => @posts.size, :rows => @posts.map{|x| x.attributes}).to_json } }
end
end
也就是说:key:rows的值必须是一个数组对象!
感谢hoooopo!