panko_serializer
panko_serializer copied to clipboard
how to customize association sorting?
Hi, I would like to know how to add customize sorting logic in has_many association?
class UserSerializer < Panko::Serializer
has_many :posts, each_serializer: PostSerializer
# posts array need to be order by published_at, for exmaple
end
class User < ApplicationRecord
has_many :posts
end
Hi @simoniong
Panko doesn't have any option to allow specific sorting in serializer, the only way you can do it - is like that:
class UserSerializer < Panko::Serializer
has_many :posts_sorted_by_created_at, name: :posts, each_serializer: PostSerializer
# posts array need to be order by published_at, for exmaple
end
class User < ApplicationRecord
has_many :posts
def posts_sorted_by_created_at
# Sort the posts here
# Suggesting to check if `posts.loaded?` is true and then use `sort_by` otherwise use `order(created_at: :desc)` for example
end
end
If you have any suggestions on how to make this use-case simpler by changing panko - let me know, I am open to ideas :)
you should be able to override the association just like you can in the attributes/fields, no ?