Why am I getting circular reference exception when calling to_json in ActiveRecord :: Relation

In Rails 3 (beta 3 on 1.8.7), when I call to_json on a relation, I get a circular reference exception. Convert this relation to an array first, and THEN calls to_json.

Failed to execute code:

Model.where (). to_json (Where model is any model in your Rails 3 application)

Code that works:

Model.where (). To_a.to_json

This can be reproduced on the console.

Anyone else working with this? Is this expected?

+2


a source to share


2 answers


I ran into this too. It looks like it was resolved in this commit:



http://github.com/rails/rails/commit/eb04408a20628a49296e0859425940b39a83ec63

0


a source


I had the same problem, I couldn't fix it, but figured 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 an XML format for the response, then Hash it, and then format it to JSON.

This approach gave me more than expected as the JSON formatted results now have exactly the same data as the XML formatted ones.

0


a source







All Articles