Skip to content

Commit 822e006

Browse files
benebricelgebhardt
authored andcommitted
Add custom key_name management for polymorphic association
Just add `foreign_key_type_changed: true` to your association key work (`has_one` or `has_many`) This closes #1285 Signed-off-by: Brice <brice.bene@gmail.com>
1 parent e520fbb commit 822e006

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

lib/jsonapi/resource_serializer.rb

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -468,16 +468,20 @@ def relationship_object(source, relationship, include_linkage = false)
468468

469469
# Extracts the foreign key value for a to_one relationship.
470470
def foreign_key_value(source, relationship)
471-
related_resource_id = if source.preloaded_fragments.has_key?(format_key(relationship.name))
472-
source.preloaded_fragments[format_key(relationship.name)].values.first.try(:id)
473-
elsif source.respond_to?("#{relationship.name}_id")
474-
# If you have direct access to the underlying id, you don't have to load the relationship
475-
# which can save quite a lot of time when loading a lot of data.
476-
# This does not apply to e.g. has_one :through relationships.
477-
source.public_send("#{relationship.name}_id")
478-
else
479-
source.public_send(relationship.name).try(:id)
480-
end
471+
# If you have changed the key_name, don't even try to look at `"#{relationship.name}_id"`
472+
# just load the association and call the custom key_name
473+
foreign_key_type_changed = relationship.options[:foreign_key_type_changed] || false
474+
related_resource_id =
475+
if source.preloaded_fragments.has_key?(format_key(relationship.name))
476+
source.preloaded_fragments[format_key(relationship.name)].values.first.try(:id)
477+
elsif !foreign_key_type_changed && source.respond_to?("#{relationship.name}_id")
478+
# If you have direct access to the underlying id, you don't have to load the relationship
479+
# which can save quite a lot of time when loading a lot of data.
480+
# This does not apply to e.g. has_one :through relationships.
481+
source.public_send("#{relationship.name}_id")
482+
else
483+
source.public_send(relationship.name).try(:id)
484+
end
481485
return nil unless related_resource_id
482486
@id_formatter.format(related_resource_id)
483487
end

0 commit comments

Comments
 (0)