Implicit detection for has_many serializer

This commit is contained in:
Adman65 2011-12-09 16:16:09 +01:00
parent 09ddc79ce0
commit 2c240cf2e0
2 changed files with 26 additions and 0 deletions

View File

@ -138,6 +138,8 @@ module ActiveModel
# to determine the serializer # to determine the serializer
if options[:key] && !options[:serializer] if options[:key] && !options[:serializer]
options[:serializer] = const_get("#{options[:key].to_s.camelize.singularize}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 else
options[:serializer] ||= const_get("#{attr.to_s.camelize}Serializer") options[:serializer] ||= const_get("#{attr.to_s.camelize}Serializer")
end end

View File

@ -211,6 +211,30 @@ class SerializerTest < ActiveModel::TestCase
}, json) }, json)
end 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 def test_overridden_associations
author_serializer = Class.new(ActiveModel::Serializer) do author_serializer = Class.new(ActiveModel::Serializer) do
attributes :first_name attributes :first_name