Allow referencing sideloaded include by key. (#2136)

* If a `key` is set on the reflection use the `key` instead of `name`.
This ensures that associations with a key set are still included.
This commit is contained in:
Christian 2017-05-18 13:59:14 -07:00 committed by Benjamin Fleischer
parent a5ab62fd18
commit a89e78c655
3 changed files with 34 additions and 3 deletions

View File

@ -5,6 +5,7 @@
Breaking changes:
Features:
- [#2136](https://github.com/rails-api/active_model_serializers/pull/2136) Enable inclusion of sideloaded relationship objects by `key`. (@caomania)
- [#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)

View File

@ -140,7 +140,7 @@ module ActiveModel
def include_data?(include_slice)
include_data_setting = options[:include_data_setting]
case include_data_setting
when :if_sideloaded then include_slice.key?(name)
when :if_sideloaded then include_slice.key?(options.fetch(:key, name))
when true then true
when false then false
else fail ArgumentError, "Unknown include_data_setting '#{include_data_setting.inspect}'"

View File

@ -6,7 +6,7 @@ module ActiveModel
class JsonApi
class IncludeParamTest < ActiveSupport::TestCase
IncludeParamAuthor = Class.new(::Model) do
associations :tags, :posts
associations :tags, :posts, :roles
end
class CustomCommentLoader
@ -51,14 +51,19 @@ module ActiveModel
include_data :if_sideloaded
IncludeParamAuthorSerializer.comment_loader.all
end
has_many :roles, key: :granted_roles do
include_data :if_sideloaded
end
end
def setup
IncludeParamAuthorSerializer.comment_loader = Class.new(CustomCommentLoader).new
@tag = Tag.new(id: 1337, name: 'mytag')
@role = Role.new(id: 1337, name: 'myrole')
@author = IncludeParamAuthor.new(
id: 1337,
tags: [@tag]
tags: [@tag],
roles: [@role]
)
end
@ -105,6 +110,31 @@ module ActiveModel
assert_equal(expected, hash[:included])
end
def test_sideloads_included_when_using_key
expected = [
{
id: '1337',
type: 'roles',
attributes: {
name: 'myrole',
description: nil,
slug: 'myrole-1337'
},
relationships: {
author: { data: nil }
}
}
]
hash = result(include: :granted_roles)
assert_equal(expected, hash[:included])
end
def test_sideloads_not_included_when_using_name_when_key_defined
hash = result(include: :roles)
assert_nil(hash[:included])
end
def test_nested_relationship
expected = {
data: [