Fix 0.10.6 regression; make using belongs_to on self opt-in

This commit is contained in:
Benjamin Fleischer 2017-11-06 22:04:50 -06:00
parent 00a47d3da4
commit 3dd6cccb4d
3 changed files with 19 additions and 1 deletions

View File

@ -57,6 +57,7 @@ still prefer the render option `:key_transform` over this setting.
application, setting `config.key_transform` to `:unaltered` will provide a performance boost.* application, setting `config.key_transform` to `:unaltered` will provide a performance boost.*
##### default_includes ##### default_includes
What relationships to serialize by default. Default: `'*'`, which includes one level of related What relationships to serialize by default. Default: `'*'`, which includes one level of related
objects. See [includes](adapters.md#included) for more info. objects. See [includes](adapters.md#included) for more info.
@ -162,6 +163,21 @@ Default: `{}`.
*Used when `jsonapi_include_toplevel_object` is `true`* *Used when `jsonapi_include_toplevel_object` is `true`*
##### jsonapi_use_foreign_key_on_belongs_to_relationship
When true, the relationship will determine its resource object identifier
without calling the association or its serializer. This can be useful when calling
the association object is triggering unnecessary queries.
For example, if a `comment` belongs to a `post`, and the comment
uses the foreign key `post_id`, we can determine the resource object
identifier `id` as `comment.post_id` and the `type` from the association options.
Or quite simply, it behaves as `belongs_to :post, type: :posts, foreign_key: :post_id`.
Note: This option has *no effect* on polymorphic associations as we cannot reliably
determine the associated object's type without instantiating it.
Default: `false`.
## Hooks ## Hooks

View File

@ -142,6 +142,7 @@ module ActiveModel
# Make JSON API top-level jsonapi member opt-in # Make JSON API top-level jsonapi member opt-in
# ref: http://jsonapi.org/format/#document-top-level # ref: http://jsonapi.org/format/#document-top-level
config.jsonapi_include_toplevel_object = false config.jsonapi_include_toplevel_object = false
config.jsonapi_use_foreign_key_on_belongs_to_relationship = false
config.include_data_default = true config.include_data_default = true
# For configuring how serializers are found. # For configuring how serializers are found.

View File

@ -94,7 +94,8 @@ module ActiveModelSerializers
end end
def belongs_to_id_on_self?(association) def belongs_to_id_on_self?(association)
association.belongs_to? && parent_serializer.config.jsonapi_use_foreign_key_on_belongs_to_relationship &&
association.belongs_to? &&
parent_serializer.object.respond_to?(association.reflection.foreign_key) parent_serializer.object.respond_to?(association.reflection.foreign_key)
end end
end end