Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

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

Open
arenoir opened this Issue · 6 comments

6 participants

@arenoir

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 arenoir referenced this issue from a commit in arenoir/active_model_serializers
@arenoir arenoir add tests demonstrating issue #548 6d450fe
@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.
@arenoir

#490 is a similar issue.

@steveklabnik steveklabnik added the bug label
@steveklabnik

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

@adamesque

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

@Tmw

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

Still an issue! Need a pull request?

@pierrea

I still have the issue as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.