jsonapi-serializer - Return slug instead of id for relationship

103 views Asked by At

I'm using jsonapi-serializer to serialize my objects.

I want to return slug for the original model and also all the association(relations).

product_serializer.rb

class ProductSerializer < V1::BaseSerializer
    set_id :slug
    set_type :product
    attributes :name, :description, :original_price_cents, :discounted_price_cents

    belongs_to :seller
  end

seller_serializer.rb

class SellerSerializer < V1::BaseSerializer
    set_id :slug
    set_type :seller
    attributes :average_rating, :reviews_count, :total_sold_count, :name
end

The problem is, the association with seller is returning the seller's id.

"data": {
            "id": "sleek-leather-keyboard-women-s-fashion-shoes",
            "type": "product",
            "attributes": {
                "name": "Sleek Leather Keyboard",
                "description": "Non qui est. Est quis molestiae.",
                "original_price_cents": 7662,
                "discounted_price_cents": 5103,
            },
            "relationships": {
                "seller": {
                    "data": {
                        "id": "1",
                        "type": "seller"
                    }
                },
            }
        },

I want to hide the seller's id 1 from above response. I tried a few things, but nothing seems to help. Anyone has any suggestion?

Doesn't work

class ProductSerializer

  belongs_to :seller do |serializer, seller|
    serializer.slug_for(seller)
  end

  private

  def self.slug_for(relationship)
    { id: relationship.slug }
  end
end

Update:

There is a id_method_name , which can be used to override this.

 belongs_to :seller, id_method_name: :slug

But it'll pick product's slug, and not seller's slug.

0

There are 0 answers