Why do i get a circular reference exception when calling to_json on an ActiveRecord::Relation
In Rails 3 (beta 3 on 1.8.7), when calling to_json on a relation i get a circular reference exc开发者_如何转开发eption. Converting that relation to an array first, and THEN calling to_json works.
Code That fails:
Model.where().to_json (Where model is any model in your Rails 3 app)
Code that works:
Model.where().to_a.to_json
This can be reproed on the console.
Has anyone else run in to this? Is this expected?
I also ran into this. Looks like it was resolved in this commit:
http://github.com/rails/rails/commit/eb04408a20628a49296e0859425940b39a83ec63
I had the same issue, couldn't fix it but found out how to avoid it, with the following:
respond_to do |format|
response = @product.to_xml
format.xml { render :xml => response }
format.json { render :json => Hash.from_xml( response ).to_json }
end
The idea here is to generate the XML format of the response, then Hash it, then format it to JSON.
This approach gave me more than expected, since now JSON formatted results have exactly the same data as XML formatted ones.
精彩评论