Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

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>
  • Loading branch information...
commit 571cb1ddc6692ed96e04a14e670beb01ba8c93ca 1 parent 3401311
@mislav mislav authored josevalim committed
View
4 activerecord/lib/active_record/relation.rb
@@ -10,7 +10,7 @@ class Relation
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 @@ def to_a
@records
end
+ def as_json(options = nil) to_a end #:nodoc:
+
# Returns size of the records.
def size
loaded? ? @records.length : count
View
7 activerecord/test/cases/json_serialization_test.rb
@@ -201,4 +201,11 @@ def test_should_allow_options_for_hash_of_authors
}
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
Please sign in to comment.
Something went wrong with that request. Please try again.