Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions lib/fast_jsonapi/relationship.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
27 changes: 25 additions & 2 deletions spec/lib/object_serializer_class_methods_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down