Skip to content

Proposal for imposing order on relationships #104

Description

@multiplegeorges

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?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions