Search code examples
ruby-on-railsrubyactive-model-serializersserialization

Is there anyway to use `options` outside of an instance method in rails ActiveSerializer?


I have a serializer that is starting to get database query heavy, but not all of the queries are needed every time the serializer is called. I would like to pass a URL param to the serializer to let it know if a certain association is needed. However, I can't seem to find a way to call options unless I am inside of an instead method. Am I going about this the wrong way? Basic example:

class UserSerializer < ActiveModel::Serializer has_many :notes, serializer: UserNotesSerializer if options['include_notes'] end

EDIT the returned error is:

*** NameError Exception: undefined local variable or method `options' for UserSerializer

Second Edit: @options is returning nil for some reason, preventing me from accessing the options hash. Is this a known problem? Using version 0.8.1

is something like this possible?


Solution

  • @options doesn't exist at the class-level. Ruby evaluates your serializer class and method definitions first. Then you create an options hash which is passed into a new instance of your serializer class when you render. The method for accessing these options is actually named instance_options in later versions of ActiveModel::Serializer.

    But, you can still accomplish what you're trying to. The most straightforward way would be to use the except: option when rendering. Instead of passing include_notes: false you can pass except: [:notes] when you don't need the association.