Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal for imposing order on relationships #104

Open
multiplegeorges opened this issue Apr 13, 2017 · 1 comment
Open

Proposal for imposing order on relationships #104

multiplegeorges opened this issue Apr 13, 2017 · 1 comment

Comments

@multiplegeorges
Copy link

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?

@fotinakis
Copy link
Owner

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants