13

I'm trying to sideload data in active_model_serializer for an Ember application and get a NoMethodError when I attempt to include the objects:

undefined method `object' for #Email:0x00000100d33d20

It only happens when :include => true is set, like this:

class ContactSerializer < ActiveModel::Serializer
  embed :ids, :include => true
  attributes :first_name, :last_name
  has_many :emails
end

My models look like this:

class Contact < ActiveRecord::Base
  attr_accessible :first_name, :last_name, :company,
  belongs_to :account
  belongs_to :user
  has_many :emails
end

class Email < ActiveRecord::Base
  attr_accessible :email_address, :email_type_id, :is_primary  
  belongs_to :contact
end

My controller looks like this:

def show
  @contact = @current_user.contacts.where(:id => params[:id]).includes(:emails).first
  render :json => @contact
end

Thanks in advance.

user1938736
  • 443
  • 4
  • 9
  • 3
    Where is your `EmailSerializer`? If you're trying to embed a serialized version of an `Email` instance, I'm pretty sure you need `Email` to have an associated serializer. `object` only exists within classes extending `ActiveModel::Serializer`. – deefour Jan 01 '13 at 01:33
  • 1
    You are right; I've been waiting for the question timeout to answer this in case anyone else has the issue. Thanks! – user1938736 Jan 02 '13 at 01:26

1 Answers1

26

As Deefour mentioned above, make sure you have a serializer for any sideloaded objects. In this case, creating EmailSerializer:

class EmailSerializer < ActiveModel::Serializer
  attributes :id, :email_address
end
user1938736
  • 443
  • 4
  • 9
  • Exactly the problem and solution for me. I do love it when an error clearly tells you what's wrong! ;) Had the error complained about a missing `EmailSerializer` class, I would have immediately got what I'd done wrong! – Nick Jul 28 '16 at 22:25