require 'jsonapi/serializer'
require 'json'
class Inner
attr_accessor :key
def initialize(key)
@key = key
end
end
class InnerSerializer
include ::JSONAPI::Serializer
set_type :inner
set_id :key
end
class Outer
attr_accessor :key, :inners
def initialize(key, inners)
@key = key
@inners = inners
end
end
class OuterSerializer
include ::JSONAPI::Serializer
set_type :outer
set_id :key
# Ideally this would "just work"
# has_many :inners
# Unfortunately we have to add a block because inner_ids doesn't exist
# This seems like another possible streamline option
# try inner if inner_ids doesn't exist - though it might be a performance thing?
# has_many :inners, &:inners
# Then we need to add id_method_name - even though it is specified in the serializer
# Is this a performance thing as well? Is looking up the serializer slow?
# This works, but duplicating setting `:key` is not very DRY
has_many :inners, id_method_name: :key, &:inners
end
outer = Outer.new('outer', [Inner.new('inner1'), Inner.new('inner2')])
puts JSON.pretty_unparse(OuterSerializer.new(outer, { include: [:inners] }).serializable_hash)
Expected Behavior
The id method specified by the serializer via
set_idwill be used instead of requiringid_method_nameto be specified.Actual Behavior
in 'public_send': undefined method 'id' for #<Inner:0x00007fa2f5860b88 @key="inner1"> (NoMethodError)
Steps to Reproduce the Problem
Specifications