panko_serializer icon indicating copy to clipboard operation
panko_serializer copied to clipboard

how to customize association sorting?

Open simoniong opened this issue 3 years ago • 2 comments

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

simoniong avatar Jul 29 '20 12:07 simoniong

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 :)

yosiat avatar Oct 09 '20 14:10 yosiat

you should be able to override the association just like you can in the attributes/fields, no ?

vasilakisfil avatar Jun 28 '21 10:06 vasilakisfil