开发者

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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜