Permalink
Browse files

Implicit detection for has_many serializer

  • Loading branch information...
1 parent 09ddc79 commit 2c240cf2e063251069ded14cc923125c858b0370 Adman65 committed Dec 9, 2011
Showing with 26 additions and 0 deletions.
  1. +2 −0 lib/active_model/serializer.rb
  2. +24 −0 test/serializer_test.rb
@@ -138,6 +138,8 @@ def associate(klass, attrs) #:nodoc:
# to determine the serializer
if options[:key] && !options[:serializer]
options[:serializer] = const_get("#{options[:key].to_s.camelize.singularize}Serializer")
+ elsif !options[:serializer] && klass == Associations::HasMany
+ options[:serializer] = const_get("#{attr.to_s.camelize.singularize}Serializer")
else
options[:serializer] ||= const_get("#{attr.to_s.camelize}Serializer")
end
@@ -211,6 +211,30 @@ def test_implicit_serializer
}, json)
end
+ def test_implicit_serializer_for_has_many
+ blog_with_posts = Class.new(Blog) do
+ attr_accessor :posts
+ end
+
+ blog_serializer = Class.new(ActiveModel::Serializer) do
+ const_set(:PostSerializer, PostSerializer)
+ has_many :posts
+ end
+
+ user = User.new
+ blog = blog_with_posts.new
+ blog.posts = [Post.new(:title => 'test')]
+
+ json = blog_serializer.new(blog, user).as_json
+ assert_equal({
+ :posts => [{
+ :title => "test",
+ :body => nil,
+ :comments => []
+ }]
+ }, json)
+ end
+
def test_overridden_associations
author_serializer = Class.new(ActiveModel::Serializer) do
attributes :first_name

0 comments on commit 2c240cf

Please sign in to comment.