aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord
diff options
context:
space:
mode:
authorMislav Marohnić <mislav.marohnic@gmail.com>2010-07-08 22:17:21 +0200
committerJosé Valim <jose.valim@gmail.com>2010-07-13 08:09:28 +0200
commit571cb1ddc6692ed96e04a14e670beb01ba8c93ca (patch)
tree0fddb6ca18f36398a3087d2e3bcf311d7720234a /activerecord
parent34013115626b2632ffe8ec357e2c5f47cfa059b2 (diff)
downloadrails-571cb1ddc6692ed96e04a14e670beb01ba8c93ca.tar.gz
rails-571cb1ddc6692ed96e04a14e670beb01ba8c93ca.tar.bz2
rails-571cb1ddc6692ed96e04a14e670beb01ba8c93ca.zip
enable AS::JSON.encode to encode AR::Relation by providing `as_json` method
[#5073 state:resolved] Signed-off-by: José Valim <jose.valim@gmail.com>
Diffstat (limited to 'activerecord')
-rw-r--r--activerecord/lib/active_record/relation.rb4
-rw-r--r--activerecord/test/cases/json_serialization_test.rb7
2 files changed, 10 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index d9fc1b4940..7499100f55 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -10,7 +10,7 @@ module ActiveRecord
include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches
- delegate :to_xml, :to_json, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to => :to_a
+ delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to => :to_a
delegate :insert, :to => :arel
attr_reader :table, :klass
@@ -74,6 +74,8 @@ module ActiveRecord
@records
end
+ def as_json(options = nil) to_a end #:nodoc:
+
# Returns size of the records.
def size
loaded? ? @records.length : count
diff --git a/activerecord/test/cases/json_serialization_test.rb b/activerecord/test/cases/json_serialization_test.rb
index c275557da8..2bc746c0b8 100644
--- a/activerecord/test/cases/json_serialization_test.rb
+++ b/activerecord/test/cases/json_serialization_test.rb
@@ -201,4 +201,11 @@ class DatabaseConnectedJsonEncodingTest < ActiveRecord::TestCase
}
assert_equal %({"1":{"author":{"name":"David"}}}), ActiveSupport::JSON.encode(authors_hash, :only => [1, :name])
end
+
+ def test_should_be_able_to_encode_relation
+ authors_relation = Author.where(:id => [@david.id, @mary.id])
+
+ json = ActiveSupport::JSON.encode authors_relation, :only => :name
+ assert_equal '[{"author":{"name":"David"}},{"author":{"name":"Mary"}}]', json
+ end
end