Implement has_many

This commit is contained in:
Santiago Pastorino
2013-08-16 23:14:59 -03:00
parent fa61314d0e
commit 61a1669a86
4 changed files with 113 additions and 3 deletions

View File

@@ -36,6 +36,16 @@ module ActiveModel
end
def has_one(*attrs)
associate(Association::HasOne, *attrs)
end
def has_many(*attrs)
associate(Association::HasMany, *attrs)
end
private
def associate(klass, *attrs)
options = attrs.extract_options!
attrs.each do |attr|
@@ -47,7 +57,7 @@ module ActiveModel
end
end
@_associations << Association::HasOne.new(attr, options)
@_associations << klass.new(attr, options)
end
end
end
@@ -76,12 +86,20 @@ module ActiveModel
hash[association.key] = serialize_ids association
end
if association.embed_objects?
associated_data = send(association.name)
hash[association.embedded_key] = association.build_serializer(associated_data).serializable_hash
hash[association.embedded_key] = serialize association
end
end
end
def serialize(association)
associated_data = send(association.name)
if associated_data.respond_to?(:to_ary)
associated_data.map { |elem| association.build_serializer(elem).serializable_hash }
else
association.build_serializer(associated_data).serializable_hash
end
end
def serialize_ids(association)
associated_data = send(association.name)
if associated_data.respond_to?(:to_ary)

View File

@@ -47,6 +47,16 @@ module ActiveModel
name
end
end
class HasMany < Association
def key
"#{name.singularize}_ids"
end
def embedded_key
name
end
end
end
end
end