diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 19e6a3fb..a0851fe8 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -124,12 +124,9 @@ module ActiveModel end def serialize_ids - # Use pluck or select_columns if available - # return collection.ids if collection.respond_to?(:ids) - ids_key = "#{key.to_s.singularize}_ids" - - if !option(:include) && !option(:embed_key) && source_serializer.object.respond_to?(ids_key) - source_serializer.object.send(ids_key) + ids_key = "#{@name.to_s.singularize}_ids".to_sym + if !option(:embed_key) && source_serializer.object.respond_to?(ids_key) + source_serializer.object.read_attribute_for_serialization(ids_key) else associated_object.map do |item| item.read_attribute_for_serialization(embed_key) @@ -203,6 +200,8 @@ module ActiveModel end def serialize_ids + id_key = "#{@name}_id".to_sym + if polymorphic? if associated_object { @@ -212,8 +211,8 @@ module ActiveModel else nil end - elsif !option(:embed_key) && source_serializer.object.respond_to?("#{name}_id") - source_serializer.object.send("#{name}_id") + elsif !option(:embed_key) && source_serializer.object.respond_to?(id_key) + source_serializer.object.read_attribute_for_serialization(id_key) elsif associated_object associated_object.read_attribute_for_serialization(embed_key) else diff --git a/test/association_test.rb b/test/association_test.rb index 7b1f1181..f0d27f5f 100644 --- a/test/association_test.rb +++ b/test/association_test.rb @@ -379,6 +379,56 @@ class AssociationTest < ActiveModel::TestCase assert_equal 1, serialized_times end + + def test_include_with_read_association_id_for_serialization_hook + @post_serializer_class.class_eval do + has_one :comment, :embed => :ids, :include => true + end + + association_name = nil + @post.class_eval do + define_method :read_attribute_for_serialization, lambda { |name| + association_name = name + send(name) + } + define_method :comment_id, lambda { + @attributes[:comment].id + } + end + + include_bare! :comment + + assert_equal :comment_id, association_name + + assert_equal({ + :comment_id => 1 + }, @hash) + end + + def test_include_with_read_association_ids_for_serialization_hook + @post_serializer_class.class_eval do + has_many :comments, :embed => :ids, :include => false + end + + association_name = nil + @post.class_eval do + define_method :read_attribute_for_serialization, lambda { |name| + association_name = name + send(name) + } + define_method :comment_ids, lambda { + @attributes[:comments].map(&:id) + } + end + + include_bare! :comments + + assert_equal :comment_ids, association_name + + assert_equal({ + :comment_ids => [1] + }, @hash) + end end class InclusionTest < AssociationTest