Search code examples
rubyruby-on-rails-3active-model-serializers

How to serialize a nested attribute from the result of a method?


I have 3 models User, Contract, and History.

User model:

class User < ApplicationRecord  
  has_many :histories
  has_many :contracts, through: :histories
end

Contract model:

class Contract < ApplicationRecord
  has_many :histories
  has_many :users, through: :histories
end

History model:

class History < ApplicationRecord
  belongs_to :user
  belongs_to :contract
end

I'm working with an API application and with Active Model Serializer gem. In the UserSerializer I have a method to get a specific collection of contracts like so:

class UserSerializer < ActiveModel::Serializer
  attributes :id, :email, :authentication_token, :current_contracts

  def current_contracts
    object.contracts.find_all{ |contract| contract.current_owner == object.id }
  end
end

The method works but the result is a collection of contracts with no history. Even though my contract serializer has this association in it:

class ContractSerializer < ActiveModel::Serializer
  attributes :id, :blockchain_id, :created_at, :product_name, :product_info, :price, :histories
  has_many :histories
end

The desired result is to be able to call the current_contracts method then be able to serialize contract.histories from that collection.

Is there any other way I could be approaching this?


Solution

  • Try modifying UserSerializer like this:

    class UserSerializer < ActiveModel::Serializer
      attributes :id, :email, :authentication_token
      has_many :current_contracts, each_serializer: ContractSerializer
    
      def current_contracts
        object.contracts.find_all{ |contract| contract.current_owner == object.id }
      end
    end