Force Active Model Serializer to return associatio

2019-08-23 12:32发布

问题:

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?

回答1:

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
    # ...