Skip to content

Commit a5ab62f

Browse files
authored
Merge pull request #2130 from greysteil/allow-id-overwriting
Allow serialized ID to be overwritten for belongs-to relationships
2 parents b48aeee + be7ee70 commit a5ab62f

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ Breaking changes:
77
Features:
88

99
- [#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)
10+
- [#2130](https://github.com/rails-api/active_model_serializers/pull/2130) Allow serialized ID to be overwritten for belongs-to relationships. (@greysteil)
1011

1112
Fixes:
1213

lib/active_model_serializers/adapter/json_api/relationship.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def data_for(association)
4545
def data_for_one(association)
4646
if association.belongs_to? &&
4747
parent_serializer.object.respond_to?(association.reflection.foreign_key)
48-
id = parent_serializer.object.send(association.reflection.foreign_key)
48+
id = parent_serializer.read_attribute_for_serialization(association.reflection.foreign_key)
4949
type = association.reflection.type.to_s
5050
ResourceIdentifier.for_type_with_id(type, id, serializable_resource_options)
5151
else

test/serializers/associations_test.rb

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,36 @@ def blog_id
165165
assert_equal expected, actual
166166
end
167167

168+
class ExternalBlog < Blog
169+
attributes :external_id
170+
end
171+
class BelongsToExternalBlogModel < ::Model
172+
attributes :id, :title, :external_blog_id
173+
associations :external_blog
174+
end
175+
class BelongsToExternalBlogModelSerializer < ActiveModel::Serializer
176+
type :posts
177+
belongs_to :external_blog
178+
179+
def external_blog_id
180+
object.external_blog.external_id
181+
end
182+
end
183+
184+
def test_belongs_to_allows_id_overwriting
185+
attributes = {
186+
id: 1,
187+
title: 'Title',
188+
external_blog: ExternalBlog.new(id: 5, external_id: 6)
189+
}
190+
post = BelongsToExternalBlogModel.new(attributes)
191+
192+
actual = serializable(post, adapter: :json_api, serializer: BelongsToExternalBlogModelSerializer).as_json
193+
expected = { data: { id: '1', type: 'posts', relationships: { :'external-blog' => { data: { id: '6', type: 'external-blogs' } } } } }
194+
195+
assert_equal expected, actual
196+
end
197+
168198
class InlineAssociationTestPostSerializer < ActiveModel::Serializer
169199
has_many :comments
170200
has_many :comments, key: :last_comments do

0 commit comments

Comments
 (0)