Skip to content

Convert id_method_name to foreign_key #45

@christophersansone

Description

@christophersansone

The option id_method_name is confusing, and it is currently referring to two different things:

  1. When polymorphic is not specified, then id_method_name is the property name for the foreign key lookup, e.g. user.document_ids.

  2. When polymorphic is specified, then id_method_name is assumed to be the primary key of the related object, e.g. user.documents.map(&:id).

Let's consider changing id_method_name to simply foreign_key. This is similar to ActiveRecord, and it is more clear that it should refer to the foreign key rather than the primary key.

class UserSerializer

  # the `foreign_key` becomes `company_id` by default
  belongs_to :company

  # the `foreign_key` becomes `document_ids` by default
  has_many :documents

end

So has_many relationships are automatically pluralized by default. And of course, the default value can be overridden with options[:foreign_key].

The library also needs some clear logic to understand when the foreign key can be used vs. when it needs to read the related object(s). At first glance, it seems like it should read the related objects under the following conditions:

  • The serializer is dynamic (i.e. polymorphic or a Proc), and options[:foreign_key] is not specified.
  • The relationship is defined with a block, and options[:foreign_key] is not specified.
  • The record does not respond to the property, e.g. user.respond_to?('document_ids')

In all other cases, it should use the foreign key.

Lastly, when the serializer does need to read the related object(s), it should determine its ID property name using its serializer's set_id value. It should not attempt to use the foreign key.

I believe we can effectively deprecate id_method_name and use this methodology instead.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions