ruby-on-rails

Two Ways to Include Associated Models in a Serializer


This is My Models.

class Patient < ApplicationRecord
  has_many :patient_segments
  has_many :segments, through: :patient_segments
end

class Segment < ApplicationRecord
  has_many :patient_segments
  has_many :patients, through: :patient_segments
end

class PatientSegment < ApplicationRecord
  belongs_to :patient
  belongs_to :segment
end

So, Patient has many segments and also Segment has many Patients. and I made some PatientSerializer and I think there is two way to include segment in PatientSerializer

First Way

class PatientSerializer < ActiveModel::Serializer
  attributes :id,
             :name,
             :description
  has_many :segments
end

Second Way

class PatientSerializer < ActiveModel::Serializer
  attributes :id,
             :name,
             :description,
             :segments
end

I think both of these approaches work well, but I'm not sure which one to use. Are there any differences between the two methods, and is one preferred over the other?


Solution

  • Using has_many :segments is preferable as you're letting the serializer know that it's an association. This is important if you need more control later of how the assocation is serialized or if you're serializing to a format such as JSONAPI.org where assocations are handled differently than normal attributes.

    // ...
    {
      "type": "articles",
      "id": "1",
      "attributes": {
        "title": "Rails is Omakase"
      },
      "relationships": {
        "author": {
          "links": {
            "self": "/articles/1/relationships/author",
            "related": "/articles/1/author"
          },
          "data": { "type": "people", "id": "9" }
        }
      }
    }
    // ...
    

    If you just pass the method name of the assocation to attributes the serializer will just call the method and try to make sense of the result. This works when you're just shooting out simple JSON but falls apart with complexity.

    Also unfortunately ActiveModelSerializers is being discontinued so you really need to start considering alternatives going forward.