diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 5ab3bcc1..07ac2a7a 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -180,11 +180,20 @@ module ActiveModel end end - associations = _associations.inject({}) do |hash, (attr,association_class)| + associations = {} + _associations.each do |attr, association_class| association = association_class.new(attr, self) - model_association = klass.reflect_on_association(association.name) - hash.merge association.key => { model_association.macro => model_association.name } + if model_association = klass.reflect_on_association(association.name) + # Real association. + associations[association.key] = { model_association.macro => model_association.name } + else + # Computed association. We could infer has_many vs. has_one from + # the association class, but that would make it different from + # real associations, which read has_one vs. belongs_to from the + # model. + associations[association.key] = nil + end end { :attributes => attrs, :associations => associations } diff --git a/test/serializer_test.rb b/test/serializer_test.rb index 17c2da3d..43150927 100644 --- a/test/serializer_test.rb +++ b/test/serializer_test.rb @@ -678,11 +678,13 @@ class SerializerTest < ActiveModel::TestCase define_method(:model_class) do model end end - # Computed attribute; not a column. + # Computed attributes (not real columns or associations). def can_edit; end + def drafts; end attributes :name, :age, :can_edit has_many :posts, :serializer => Class.new + has_many :drafts, :serializer => Class.new has_one :parent, :serializer => Class.new end @@ -690,6 +692,7 @@ class SerializerTest < ActiveModel::TestCase :attributes => { :name => :string, :age => :integer, :can_edit => nil }, :associations => { :posts => { :has_many => :posts }, + :drafts => nil, :parent => { :belongs_to => :parent } } }