diff --git a/lib/fast_jsonapi/relationship.rb b/lib/fast_jsonapi/relationship.rb index 7a038de7..8c659bdb 100644 --- a/lib/fast_jsonapi/relationship.rb +++ b/lib/fast_jsonapi/relationship.rb @@ -47,8 +47,11 @@ def serialize(record, serialization_params, output_hash) end def fetch_associated_object(record, params) - return object_block.call(record, params) unless object_block.nil? - record.send(object_method_name) + if object_block.present? + object_block.arity.abs == 1 ? object_block.call(record) : object_block.call(record, params) + else + record.send(object_method_name) + end end def include_relationship?(record, serialization_params) @@ -96,7 +99,7 @@ def id_hash(id, record_type, default_return=false) def fetch_id(record, params) if object_block.present? - object = object_block.call(record, params) + object = object_block.arity.abs == 1 ? object_block.call(record) : object_block.call(record, params) return object.map { |item| item.public_send(id_method_name) } if object.respond_to? :map return object.try(id_method_name) end diff --git a/spec/lib/object_serializer_class_methods_spec.rb b/spec/lib/object_serializer_class_methods_spec.rb index 6fe4718b..fd6c367f 100644 --- a/spec/lib/object_serializer_class_methods_spec.rb +++ b/spec/lib/object_serializer_class_methods_spec.rb @@ -102,8 +102,31 @@ subject(:hash) { MovieSerializer.new(movie).serializable_hash } it 'returns correct hash where id is obtained from the method specified via `id_method_name`' do - expected_award_data = movie.actors.map(&:awards).flatten.map do |actor| - { id: actor.imdb_award_id.to_s, type: actor.class.name.downcase.to_sym } + expected_award_data = movie.actors.map(&:awards).flatten.map do |award| + { id: award.imdb_award_id.to_s, type: award.class.name.downcase.to_sym } + end + serialized_award_data = hash[:data][:relationships][:awards][:data] + + expect(serialized_award_data).to eq(expected_award_data) + end + end + end + + describe '#has_many with proc and id_method_name' do + before do + ActorSerializer.has_many(:awards, id_method_name: :imdb_award_id, &:awards) + end + + after do + ActorSerializer.relationships_to_serialize.delete(:awards) + end + + context 'awards is not included' do + subject(:hash) { ActorSerializer.new(actor).serializable_hash } + + it 'returns correct hash where id is obtained from the method specified via `id_method_name`' do + expected_award_data = actor.awards.flatten.map do |award| + { id: award.imdb_award_id.to_s, type: award.class.name.downcase.to_sym } end serialized_award_data = hash[:data][:relationships][:awards][:data]