From a701777bd5b082e9348eb41d1d50a635acd81999 Mon Sep 17 00:00:00 2001 From: Yohan Robert Date: Wed, 25 May 2016 02:46:22 +0200 Subject: [PATCH] Prevent loading association when include_data is set to false (#1710) This should fix #1707. --- CHANGELOG.md | 2 ++ lib/active_model/serializer/reflection.rb | 6 +++--- test/adapter/json_api/relationships_test.rb | 13 +++++++++---- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d49d07ad..f2a8e2bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ Breaking changes: Features: Fixes: +- [#1710](https://github.com/rails-api/active_model_serializers/pull/1710) Prevent association loading when `include_data` option + is set to `false`. (@groyoh) Misc: - [#1734](https://github.com/rails-api/active_model_serializers/pull/1734) Adds documentation for conditional attribute (@lambda2) diff --git a/lib/active_model/serializer/reflection.rb b/lib/active_model/serializer/reflection.rb index aba75a35..fbc421f7 100644 --- a/lib/active_model/serializer/reflection.rb +++ b/lib/active_model/serializer/reflection.rb @@ -75,10 +75,10 @@ module ActiveModel if block block_value = instance_exec(serializer, &block) - if block_value == :nil - serializer.read_attribute_for_serialization(name) - else + if block_value != :nil block_value + elsif @_include_data + serializer.read_attribute_for_serialization(name) end else serializer.read_attribute_for_serialization(name) diff --git a/test/adapter/json_api/relationships_test.rb b/test/adapter/json_api/relationships_test.rb index 5fa0de8d..c0656cf1 100644 --- a/test/adapter/json_api/relationships_test.rb +++ b/test/adapter/json_api/relationships_test.rb @@ -5,7 +5,8 @@ module ActiveModel module Adapter class JsonApi class RelationshipTest < ActiveSupport::TestCase - RelationshipAuthor = Class.new(::Model) + class RelationshipAuthor < ::Model; end + class RelationshipAuthorSerializer < ActiveModel::Serializer has_one :bio do link :self, '//example.com/link_author/relationships/bio' @@ -71,7 +72,6 @@ module ActiveModel def setup @post = Post.new(id: 1337, comments: [], author: nil) - @blog = Blog.new(id: 1337, name: 'extra') @bio = Bio.new(id: 1337) @like = Like.new(id: 1337) @role = Role.new(id: 'from-record') @@ -82,7 +82,6 @@ module ActiveModel @author = RelationshipAuthor.new( id: 1337, posts: [@post], - blog: @blog, reviewer: @reviewer, bio: @bio, likes: [@like], @@ -158,10 +157,16 @@ module ActiveModel end def test_relationship_not_including_data + @author.define_singleton_method(:read_attribute_for_serialization) do |attr| + fail 'should not be called' if attr == :blog + super(attr) + end expected = { links: { self: '//example.com/link_author/relationships/blog' } } - assert_relationship(:blog, expected) + assert_nothing_raised do + assert_relationship(:blog, expected) + end end def test_relationship_including_data_explicit