FAQ / Troubleshooting

Can I use Mutils without Rails?

Yes. Runtime serialization only requires require "mutils".

Do I need a serializer for relationships?

Yes. belongs_to, has_one, and has_many require serializer:.

If you omit it, Mutils raises an error when the serializer class is defined.

Why is a field missing from the output?

Check which declaration you used:

  • attributes are included by default
  • custom_methods are included by default
  • attribute is optional by default
  • custom_method is optional by default
  • relationships are optional by default

For optional entries, pass includes: or set always_include: true.

Why is my conditional field missing?

Check:

  • your if: value is a Proc
  • the proc logic matches the object being serialized
  • any expected params: were passed to the serializer

Example:

UserSerializer.new(user, params: { show_email: true }).to_h

Why did Mutils raise if: should be a Proc object?

Because if: only accepts a proc:

attribute :email, if: proc { |scope| scope.admin? }

What does scope refer to?

scope is the object currently being serialized. Inside serializer instance methods, use scope to read values from that object.

What happens when I pass a collection?

to_h returns an array of serialized entries. as_json can wrap the collection in a pluralized root key if root wrapping is enabled.

Why is the root key singular or plural?

Mutils uses:

  • the configured name_tag, if present
  • otherwise the serialized object’s class name

For collections, it pluralizes the chosen name.

Why is my renamed relationship not included with includes:?

Use the original relationship name in includes:, not the label: value.

Example:

belongs_to :company, serializer: CompanySerializer, label: "organization"

Request it with:

UserSerializer.new(user, includes: [:company]).to_h