Custom
Attributes don't need to map to model columns. Define a method with the same name to create a virtual attribute.
Basic Usage
ruby
class InvoiceRepresentation < Apiwork::Representation::Base
attribute :full_title, type: :string
def full_title
"#{record.status.upcase}: #{record.number}"
end
endThe record method returns the current record.
WARNING
Custom attributes require an explicit type. There is no model column to detect from.
Preloading
Custom attributes that access associations cause N+1 queries:
ruby
class InvoiceRepresentation < Apiwork::Representation::Base
attribute :item_count, type: :integer
def item_count
record.items.size # N+1: one query per invoice
end
endUse preload: to eager load associations:
ruby
class InvoiceRepresentation < Apiwork::Representation::Base
attribute :item_count, type: :integer, preload: :items
def item_count
record.items.size # Items already loaded
end
endThe format matches Rails includes:
ruby
# Single association
preload: :items
# Multiple associations
preload: [:items, :customer]
# Nested associations
preload: { items: :adjustments }Apiwork combines preloads with other includes (such as eager-loaded associations) into a single query.