Skip to content

Commit 5714478

Browse files
committed
Merge pull request cerebris#37 from arantir/master
Fix include associations which might be nil.
2 parents 8840a35 + 36ad222 commit 5714478

File tree

3 files changed

+49
-3
lines changed

3 files changed

+49
-3
lines changed

lib/jsonapi/resource.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -398,7 +398,7 @@ def _associate(klass, *attrs)
398398
resource_class = self.class.resource_for(type_name)
399399
if resource_class
400400
associated_model = @model.send attr
401-
return resource_class.new(associated_model, @context)
401+
return associated_model ? resource_class.new(associated_model, @context) : nil
402402
end
403403
end unless method_defined?(attr)
404404
elsif @_associations[attr].is_a?(JSONAPI::Association::HasMany)

test/fixtures/active_record.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ class ExpenseEntry < ActiveRecord::Base
135135

136136
class Planet < ActiveRecord::Base
137137
has_many :moons
138-
has_one :planet_type
138+
belongs_to :planet_type
139139

140140
has_and_belongs_to_many :tags, join_table: :planets_tags
141141
end
@@ -452,7 +452,7 @@ class PropertyResource < JSONAPI::Resource
452452
end
453453

454454
class PlanetTypeResource < JSONAPI::Resource
455-
attribute :name
455+
attributes :id, :name
456456
has_many :planets
457457
end
458458

test/unit/serializer/serializer_test.rb

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -549,4 +549,50 @@ def test_serializer_empty_links_null_and_array
549549
assert_match /\"planetType\":null/, json
550550
assert_match /\"moons\":\[\]/, json
551551
end
552+
553+
def test_serializer_include_with_empty_links_null_and_array
554+
planets = []
555+
Planet.find(7, 8).each do |planet|
556+
planets.push PlanetResource.new(planet)
557+
end
558+
559+
planet_hash = JSONAPI::ResourceSerializer.new.serialize_to_hash(
560+
planets,
561+
include: ['planet_type'],
562+
fields: { planet_types: [:id, :name] }
563+
)
564+
565+
assert_hash_equals(
566+
{
567+
planets: [{
568+
id: 7,
569+
name: 'Beta X',
570+
description: 'Newly discovered Planet Z',
571+
links: {
572+
planetType: 1,
573+
tags: [],
574+
moons: []
575+
}
576+
},
577+
{
578+
id: 8,
579+
name: 'Beta W',
580+
description: 'Newly discovered Planet W',
581+
links: {
582+
planetType: nil,
583+
tags: [],
584+
moons: []
585+
}
586+
}],
587+
linked: {
588+
planetTypes: [
589+
{ id: 1, name: "Gas Giant" }
590+
]
591+
}
592+
}, planet_hash)
593+
594+
json = planet_hash.to_json
595+
assert_match /\"planetType\":null/, json
596+
assert_match /\"moons\":\[\]/, json
597+
end
552598
end

0 commit comments

Comments
 (0)