From 8cba41bb6a2400faee14976175b0e991f8874277 Mon Sep 17 00:00:00 2001 From: Jose Fernandez Date: Tue, 22 Jun 2010 23:32:46 -0500 Subject: [PATCH] Adds #to_json support to ActiveRecord::Relation. Fixes the CircularReferenceError error when calling #to_json on a live AR scope --- activerecord/lib/active_record/relation.rb | 4 ++++ activerecord/test/cases/relations_test.rb | 5 +++++ 2 files changed, 9 insertions(+), 0 deletions(-) diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 66970a5..c421a64 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -101,6 +101,10 @@ module ActiveRecord @limit_value.present? ? to_a.many? : size > 1 end end + + def to_json(options = nil) + ActiveSupport::JSON.encode(to_a, options) + end # Updates all records with details given if they match a set of conditions supplied, limits and order can # also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 165b2e1..a9200cf 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -160,6 +160,11 @@ class RelationTest < ActiveRecord::TestCase assert_respond_to relation, method, "Topic.scoped should respond to #{method.inspect}" end end + + def test_scoped_to_json + json = Topic.scoped.to_json + assert_match %r{^\[\{"topic":\{}, json + end def test_respond_to_private_arel_methods relation = Topic.scoped -- 1.7.1