Skip to content
New issue

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

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested serializers: undefined method #56

Closed
coderdave opened this issue Nov 14, 2014 · 4 comments
Closed

Nested serializers: undefined method #56

coderdave opened this issue Nov 14, 2014 · 4 comments

Comments

@coderdave
Copy link
Contributor

In following the readme to set up a nested serializer, I created this AccountSerializer:

require 'oat/adapters/hal'

class AccountSerializer < Oat::Serializer
  adapter Oat::Adapters::HAL

  schema do
    map_properties :id

    entity :tasks, item.tasks do |task, task_serializer|
      task_serializer.created_at task.created_at
    end
  end
end

However, I'm getting the following error when running AccountSerializer.new(Account.first).to_json
"undefined method 'created_at' for #<ActiveRecord::Associations::CollectionProxy []>"

Am I doing something wrong?

@ismasan
Copy link
Owner

ismasan commented Nov 15, 2014

Hi.

Yes, you should be using entities (plural) instead of entity (singular), because you're trying to render an array of tasks, not a single one.

So:

require 'oat/adapters/hal'

class AccountSerializer < Oat::Serializer
  adapter Oat::Adapters::HAL

  schema do
    map_properties :id

    entities :tasks, item.tasks do |task, task_serializer|
      task_serializer.created_at task.created_at
    end
  end
end

@ismasan ismasan closed this as completed Nov 15, 2014
@coderdave
Copy link
Contributor Author

Sorry, that was the debug version I pasted in. When I use entities, I get this error:
"NoMethodError: undefined method `created_at' for #<#Class:0x00000105e69208:0x00000105e68c40>"

There is a created_at on the Task model. What else could it be?

@coderdave
Copy link
Contributor Author

The fix is to have another block for the serializer:

require 'oat/adapters/hal'

class AccountSerializer < Oat::Serializer
  adapter Oat::Adapters::HAL

  schema do
    map_properties :id

    entities :tasks, item.tasks do |task, task_serializer|
      task_serializer.properties do |props|
        props.created_at task.created_at
      end
    end
  end
end

@ismasan
Copy link
Owner

ismasan commented Nov 17, 2014

Yes. This should work to:

task_serializer.property :created_at, task.created_at

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants