diff --git a/CHANGELOG.md b/CHANGELOG.md index c0ed98b7..9313e61f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Breaking changes: Features: - [#2021](https://github.com/rails-api/active_model_serializers/pull/2021) ActiveModelSerializers::Model#attributes. Originally in [#1982](https://github.com/rails-api/active_model_serializers/pull/1982). (@bf4) +- [#2130](https://github.com/rails-api/active_model_serializers/pull/2130) Allow serialized ID to be overwritten for belongs-to relationships. (@greysteil) Fixes: diff --git a/lib/active_model_serializers/adapter/json_api/relationship.rb b/lib/active_model_serializers/adapter/json_api/relationship.rb index 5d7399a3..45cddb89 100644 --- a/lib/active_model_serializers/adapter/json_api/relationship.rb +++ b/lib/active_model_serializers/adapter/json_api/relationship.rb @@ -45,7 +45,7 @@ module ActiveModelSerializers def data_for_one(association) if association.belongs_to? && parent_serializer.object.respond_to?(association.reflection.foreign_key) - id = parent_serializer.object.send(association.reflection.foreign_key) + id = parent_serializer.read_attribute_for_serialization(association.reflection.foreign_key) type = association.reflection.type.to_s ResourceIdentifier.for_type_with_id(type, id, serializable_resource_options) else diff --git a/test/serializers/associations_test.rb b/test/serializers/associations_test.rb index c1b164b8..5d195cbc 100644 --- a/test/serializers/associations_test.rb +++ b/test/serializers/associations_test.rb @@ -165,6 +165,36 @@ module ActiveModel assert_equal expected, actual end + class ExternalBlog < Blog + attributes :external_id + end + class BelongsToExternalBlogModel < ::Model + attributes :id, :title, :external_blog_id + associations :external_blog + end + class BelongsToExternalBlogModelSerializer < ActiveModel::Serializer + type :posts + belongs_to :external_blog + + def external_blog_id + object.external_blog.external_id + end + end + + def test_belongs_to_allows_id_overwriting + attributes = { + id: 1, + title: 'Title', + external_blog: ExternalBlog.new(id: 5, external_id: 6) + } + post = BelongsToExternalBlogModel.new(attributes) + + actual = serializable(post, adapter: :json_api, serializer: BelongsToExternalBlogModelSerializer).as_json + expected = { data: { id: '1', type: 'posts', relationships: { :'external-blog' => { data: { id: '6', type: 'external-blogs' } } } } } + + assert_equal expected, actual + end + class InlineAssociationTestPostSerializer < ActiveModel::Serializer has_many :comments has_many :comments, key: :last_comments do