HasOne associations work

This commit is contained in:
Yehuda Katz 2012-01-11 12:26:49 -07:00
parent f9d0259340
commit dd0b56c748
2 changed files with 45 additions and 19 deletions

View File

@ -316,13 +316,17 @@ module ActiveModel
serializer = options[:serializer]
scope = options[:scope]
association = Associations::HasMany.new(key, { :serializer => serializer })
if value.respond_to?(:to_ary)
association = Associations::HasMany.new(key, :serializer => serializer)
else
association = Associations::HasOne.new(key, :serializer => serializer)
end
if embed == :ids
node[key] = association.serialize_ids(value, scope)
if root_embed
merge_association hash, key, association.serialize_many(value, scope, self, {})
merge_association hash, association.plural_key, association.serialize_many(value, scope, self, {})
end
elsif embed == :objects
node[key] = association.serialize(value, scope)

View File

@ -1,6 +1,6 @@
require "test_helper"
class SerializerTest < ActiveModel::TestCase
class AssociationTest < ActiveModel::TestCase
def def_serializer(&block)
Class.new(ActiveModel::Serializer, &block)
end
@ -29,39 +29,61 @@ class SerializerTest < ActiveModel::TestCase
end
end
def test_include_associations
post = Model.new(:title => "New Post", :body => "Body")
comment = Model.new(:id => 1, :body => "ZOMG A COMMENT")
post.comments = [ comment ]
def setup
@post = Model.new(:title => "New Post", :body => "Body")
@comment = Model.new(:id => 1, :body => "ZOMG A COMMENT")
@post.comments = [ @comment ]
@post.comment = @comment
comment_serializer_class = def_serializer do
@comment_serializer_class = def_serializer do
attributes :body
end
post_serializer_class = def_serializer do
@post_serializer_class = def_serializer do
attributes :title, :body
end
post_serializer = post_serializer_class.new(post, nil)
@post_serializer = @post_serializer_class.new(@post, nil)
hash = {}
root_hash = {}
post_serializer.include! :comments,
@hash = {}
@root_hash = {}
end
def test_include_bang_has_many_associations
@post_serializer.include! :comments,
:embed => :ids,
:include => true,
:hash => root_hash,
:node => hash,
:value => post.comments,
:serializer => comment_serializer_class
:hash => @root_hash,
:node => @hash,
:value => @post.comments,
:serializer => @comment_serializer_class
assert_equal({
:comments => [ 1 ]
}, hash)
}, @hash)
assert_equal({
:comments => [
{ :body => "ZOMG A COMMENT" }
]
}, root_hash)
}, @root_hash)
end
def test_include_bang_has_one_associations
@post_serializer.include! :comment,
:embed => :ids,
:include => true,
:hash => @root_hash,
:node => @hash,
:value => @post.comment,
:serializer => @comment_serializer_class
assert_equal({
:comment => 1
}, @hash)
assert_equal({
:comments => [{ :body => "ZOMG A COMMENT" }]
}, @root_hash)
end
end