Rails 4: Order has_many in serializer
Asked Answered
C

2

5

I have a serializer with a has_many association and I want to order the dependent model. For some reason I get an undefined method key?' error:

class API::ClientSerializer < ActiveModel::Serializer
    has_many :check_ins, -> { order(:week) }
end

How else do I order the check_ins by week?

Compromise answered 27/6, 2017 at 17:41 Comment(0)
T
13
class API::ClientSerializer < ActiveModel::Serializer
  has_many :check_ins do
    object.check_ins.order(:week)
  end 
end
Tatter answered 22/6, 2018 at 22:21 Comment(0)
P
2
class API::ClientSerializer < ActiveModel::Serializer
  has_many :check_ins

  def check_ins
    object.check_ins.order(:week)
  end
end
Polyzoan answered 27/6, 2017 at 17:56 Comment(2)
Funny you recommended this, this is what I ended up doing I just thought there was a way to fix the initial syntaxCompromise
Is there a way of sorting and using the check_ins serializer as well?Culmiferous

© 2022 - 2024 — McMap. All rights reserved.