0

Working on front-end and json responses on RoR backend, I'm trying to set up serializers to avoid code cluttering with :only => [] and so on.

What I find out, is that in serializer with associations we can't use name of class, which is not yet initialized.

class AuthorOnlySerializer < ActiveModel::Serializer
  attributes :id, :name, :real_name, :wiki_link
end

class BookSerializer < ActiveModel::Serializer
  has_many :authors, serializer: AuthorOnlySerializer
  attributes :id, :title, :isbn, :publish_year, :detail
end

Such code works properly, but if I switch these classes (having them in one file now) (UPD for understanding: what I mean by switching is putting BookSerializer in front of AuthorOnlySerializer in file), I'm getting

uninitialized constant BookSerializer::AuthorOnlySerializer

Is there any way to avoid these problem and to be able to put them in any order? I've tried supplying symbol instead of class into serializer option, but then comes

undefined method `new' for :AuthorOnlySerializer:Symbol

, so it doesn't support anything but classes there.

Any thoughts?

ProdoElmit
  • 1,067
  • 9
  • 22
  • when exactly does this error happen? i did not understand this part. – phoet Nov 08 '13 at 17:28
  • Error happens, when I'm trying to call something, which requires work of serializer. In this example, I was trying to call books.json , which is processed through respond_with(@books). UPD for understanding: what I mean by switching is putting BookSerializer in front of AuthorOnlySerializer in file – ProdoElmit Nov 08 '13 at 18:37

0 Answers0