Sitelet https://github.com/jsonapi-serializer/jsonapi-serializer/issues/229
Skip to content

Use the id specified by the serializer instead of requiring id_method_name to be specified. #229

Description

@royalpeasantry

Expected Behavior

The id method specified by the serializer via set_id will be used instead of requiring id_method_name to be specified.

Actual Behavior

in 'public_send': undefined method 'id' for #<Inner:0x00007fa2f5860b88 @key="inner1"> (NoMethodError)

Steps to Reproduce the Problem

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)

Specifications

  • Version: 2.2
  • Ruby version: ruby 2.7.6p219

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions