Search code examples
ruby-on-railsruby-on-rails-4activerecordserializationactive-model-serializers

Force Active Model Serializer to return association


I have a Active Model Serializer that has the following:

class API::DashboardSerializer < ActiveModel::Serializer
    attributes :id, :name, :special

    def special
        x = object.check_ins.first
        prev = x.prev_ci_with_weigh_in
    end
end

where special returns a record of class CheckIn and I'd like it to use the CheckInSerailizer for that record. How can I force it to use the CheckInSerializer in special?


Solution

  • Remove special from attributes and then try has_one or belongs_to, described in this Guide, like this:

    class API::DashboardSerializer < ActiveModel::Serializer
      attributes :id, :name
    
      has_one :special, serializer: CheckInSerializer
    
      def special
        # ...