Is it a bug for method hash#to_json in Rails?
I us开发者_如何学运维e 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
the generated json data is:
{"rows":"[{\"title\":\"ruby\",\"body\":\"goood\",\"click_count\":1,\"id\":1},{\"title\":\"g\",\"body\":\"h\",\"click_count\":1,\"id\":2}]","results":2}
but in fact is shuld be:
{"rows":[{\"title\":\"ruby\",\"body\":\"goood\",\"click_count\":1,\"id\":1},{\"title\":\"g\",\"body\":\"h\",\"click_count\":1,\"id\":2}],"results":2}
is it a bug in rails?
and now how can to_json generate the expected json data for me?
Thanks!
Sorry,it was my fault.
the action code should be
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
That is to say: the value of key :rows must be an array object!
Thanks hoooopo!
精彩评论