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

how to customize association sorting? #75

Open
simoniong opened this issue Jul 29, 2020 · 2 comments
Open

how to customize association sorting? #75

simoniong opened this issue Jul 29, 2020 · 2 comments
Labels

Comments

@simoniong
Copy link

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
@yosiat
Copy link
Owner

yosiat commented Oct 9, 2020

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 yosiat added the question label Oct 9, 2020
@vasilakisfil
Copy link

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

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

No branches or pull requests

3 participants