Skip to content

Commit

Permalink
enable AS::JSON.encode to encode AR::Relation by providing as_json
Browse files Browse the repository at this point in the history
…method
  • Loading branch information
mislav committed Jul 8, 2010
1 parent 9ac9c35 commit 59a4fe0
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
2 changes: 2 additions & 0 deletions activerecord/lib/active_record/relation.rb
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions activerecord/test/cases/json_serialization_test.rb
Expand Up @@ -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

0 comments on commit 59a4fe0

Please sign in to comment.