Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Undefined method error when serializing an array of records that include an empty has_one relationship. #548

Closed
arenoir opened this Issue Apr 17, 2014 · 7 comments

Comments

Projects
None yet
7 participants
Contributor

arenoir commented Apr 17, 2014

I am getting an undefined method error when serializing an array of records that include empty polymorphic has_one relationships.

Given a the following models

class Task < ActiveRecord::Base
   has_one :list, as: 'listable'
end

class List < ActiveRecord::Base
    belongs_to :listable, polymorphic: true
    has_many :items
end

class Items < ActiveRecord::Base
  belongs_to :list
end


class ListSerializer < ActiveModel::Serializer
  attributes :name
  has_many :items, serializer: ItemSerializer
end

class ItemSerializer < ActiveModel::Serializer
  attributes :description
end

class TaskSerializer < ActiveModel::Serializer
  has_one :list, serializer: ListSerializer
end


### test

task1 = Task.create()
task2 = Task.create()
list = List.create( listable: task1 )

ArraySerializer.new([task1, task2]) 
# returns
# NoMethodError: undefined method `items' for nil:NilClass

I have written a test that demonstrates this bug. I will do a pull request. I also noticed that the has_one relationship is not wrapped in an array if it is a polymorphic has_one relationship.

arenoir added a commit to arenoir/active_model_serializers that referenced this issue Apr 17, 2014

@arenoir arenoir changed the title from Undefined method error when serializing an array of records that include an empty polymorphic has_one relationship. to Undefined method error when serializing an array of records that include an empty has_one relationship. Apr 18, 2014

Contributor

arenoir commented Apr 18, 2014

#490 is a similar issue.

@steveklabnik steveklabnik added the bug label Aug 22, 2014

Contributor

steveklabnik commented Aug 22, 2014

This sounds like a bug. What version are you using?

I'm seeing this bug using 0.9.0 — but only with has_one and embed: :id, embed_in_root: true

Tmw commented Nov 19, 2014

Ran into a similar issue today. Took me way too long to figure it out. Saw your issue and sort-of fixed it by filtering out the empty has_one relations. http://www.rubydoc.info/github/rails-api/active_model_serializers/ActiveModel/Serializer:filter

dgdosen commented Mar 18, 2015

Still an issue! Need a pull request?

pierrea commented Mar 31, 2015

I still have the issue as well.

Owner

remear commented Mar 17, 2016

If this is still an issue for anyone, please open a PR.

@remear remear closed this Mar 17, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment