Merge pull request #2130 from greysteil/allow-id-overwriting

Allow serialized ID to be overwritten for belongs-to relationships
This commit is contained in:
Benjamin Fleischer 2017-05-15 09:24:42 -05:00 committed by GitHub
commit a5ab62fd18
3 changed files with 32 additions and 1 deletions

View File

@ -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:

View File

@ -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

View File

@ -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