-
Notifications
You must be signed in to change notification settings - Fork 148
Description
The option id_method_name is confusing, and it is currently referring to two different things:
-
When
polymorphicis not specified, thenid_method_nameis the property name for the foreign key lookup, e.g.user.document_ids. -
When
polymorphicis specified, thenid_method_nameis 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
endSo 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.