Empty hash {} is not .present? in Rails, causing count attributes to be excluded even when the controller intends to include them.
{}.present? # => false ❌Use .key?() instead of .present?() to check if the option was passed:
# Before
attribute :workspace_count, if: -> { @instance_options[:workspace_count_map].present? }
# After
attribute :workspace_count, if: -> { @instance_options.key?(:workspace_count_map) }options = { workspace_count_map: {} }
options.key?(:workspace_count_map) # => true ✅- Attribute IS included
- Method returns
workspace_count_map[object.id] || 0 - Missing IDs default to 0 ✅
options = {} # or { other: :options }
options.key?(:workspace_count_map) # => false ✅- Attribute is NOT included
- Method is never called
- No
nil[object.id]error ✅
All 156 tests in spec/controllers/api/v2/projects_controller_spec.rb pass, including:
indexwith empty results (returns 0 counts)showwith countscreatewithout count mapsupdatewithout count maps
Enables future controller optimizations where we only query projects with non-zero counts:
# Controller can return empty map for all-zero case
proj_with_workspace_count = {}
# Serializer correctly includes attribute and defaults to 0
# Before: {} not .present?, attribute excluded ❌
# After: .key?() true, attribute included ✅