Performance: Serializers (Active Model Serializers)
This affects the server response time and the size of JSON payloads sent to the browser, impacting page load speed and interaction readiness.
class UserSerializer < ActiveModel::Serializer
attributes :id, :name, :email
endclass UserSerializer < ActiveModel::Serializer
attributes :id, :name, :email, :created_at, :updated_at, :password_digest, :session_token
end| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Serializing all model attributes including sensitive data | N/A (server-side) | N/A | N/A | [X] Bad |
| Serializing only needed attributes | N/A (server-side) | N/A | N/A | [OK] Good |
| Not eager loading associations causing N+1 queries | N/A (server-side) | N/A | N/A | [X] Bad |
| Eager loading associations before serialization | N/A (server-side) | N/A | N/A | [OK] Good |
Active Model Serializers in a Rails application?attributes followed by symbols for each field.attribute (singular), attrs, and fields are not valid methods in Active Model Serializers.class UserSerializer < ActiveModel::Serializer attributes :id, :name attribute :email end
attributes (plural) and attribute (singular). Only attributes is valid; attribute is not a defined method and raises NoMethodError when the class is defined.class PostSerializer < ActiveModel::Serializer
attributes :id, :title
def title
object.title.upcase
end
def author_name
object.author.name
end
endattributes, so only these keys appear in JSON.author_name exists but is not listed in attributes, so it won't be serialized.class Article < ApplicationRecord belongs_to :author end class Author < ApplicationRecord has_many :articles end
class ArticleSerializer < ActiveModel::Serializer attributes :id, :title belongs_to :author end class AuthorSerializer < ActiveModel::Serializer attributes :id, :name end
belongs_to :author in ArticleSerializer includes the author association serialized by AuthorSerializer.Pass the test and this pattern moves unknown