jsonapi-serializers icon indicating copy to clipboard operation
jsonapi-serializers copied to clipboard

Proposal for imposing order on relationships

Open multiplegeorges opened this issue 8 years ago • 1 comments

Here's a proposal for an agnostic way of specifying how the serializer should sort the relationships specified by has_many.

class AssetSerializer < BaseSerializer
  attributes :id, :title, :folder_id, :updated_at

  attribute :medium_url do
    object.image.medium.url
  end

  attribute :large_url do
    object.image.large.url
  end

  has_one :folder
end
class FolderSerializer < BaseSerializer
  attributes :id, :title

  has_one :user
  has_many :assets, order: -> (relation) { relation.order(:updated_at) } 
end

This example obviously uses the ActiveRecord order method, but users could put anything appropriate to their ORM or data store in the block.

Internally, the gem would take the result of calling the relation name on the object and apply the block.

Right now, I can impose an order on the top-level collection, but the included relationships come out in whatever the database defaults to. This is a problem for me as I am using UUIDs as primary keys.

Furthermore, I don't want to impose the ordering on the relationship at the ORM level because I'll have to override that everywhere else in the application code.

Thoughts?

multiplegeorges avatar Apr 13 '17 14:04 multiplegeorges

jsonapi-serializers is almost 100% ORM agnostic, so I don't think this is something we should handle on our end. :/

I think you could do something like this though:

has_many :assets do
  object.assets.order(:updated_at)
end

fotinakis avatar Apr 13 '17 16:04 fotinakis