Skip to content

ActiveModel::Serializer attributes not working as expected #1988

@mikevoets

Description

@mikevoets

I am experiencing the following problem:

class Api::V1::RecordSerializer < ActiveModel::Serializer
  class << self
    def all_except_record_id
      attribs = Api::V1::Base.retrieve_attributes(:record)
      attribs - ['record_id'] if attribs
    end
  end

  attributes self.all_except_record_id
  has_many :notes
end

The problem:
When an object gets serialized, all attribute values are null even though the object has non-null values.

The workaround I have for this right now is the following:

class RecordSerializer < ActiveModel::Serializer
  ...
  self.all_except_record_id.each do |a|
    define_method(a) { object.send(a) }
  end
end

The record resource looks like the following:

class Api::V1::Base < ActiveModelSerializers::Model
  self.retrieve_attributes ... ; end
end

class Api::V1::Record < Api::V1::Base
  class << self
    def attribs
      attrs = retrieve_attributes(:record)
      attrs + ['notes'] if attrs
    end
  end

  attr_accessor(*self.attribs)
  # attributes *self.attribs does not work (NoMethodError)!
end

In my application controller, I have the following:

class ApplicationController < ActionController::API
  include ::ActionController::Serialization
  ...
end

My reports controller renders like this:

class Api::V1::RecordsController < ApplicationController
  def index
    ...
    render json: reports, status: :ok
  end
end

What am I doing wrong here?

Environment

ActiveModelSerializers Version: 0.10.3
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]
Ubuntu 16.04
Rails 5.0.0.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions