File tree Expand file tree Collapse file tree 3 files changed +49
-3
lines changed Expand file tree Collapse file tree 3 files changed +49
-3
lines changed Original file line number Diff line number Diff line change @@ -398,7 +398,7 @@ def _associate(klass, *attrs)
398
398
resource_class = self . class . resource_for ( type_name )
399
399
if resource_class
400
400
associated_model = @model . send attr
401
- return resource_class . new ( associated_model , @context )
401
+ return associated_model ? resource_class . new ( associated_model , @context ) : nil
402
402
end
403
403
end unless method_defined? ( attr )
404
404
elsif @_associations [ attr ] . is_a? ( JSONAPI ::Association ::HasMany )
Original file line number Diff line number Diff line change @@ -135,7 +135,7 @@ class ExpenseEntry < ActiveRecord::Base
135
135
136
136
class Planet < ActiveRecord ::Base
137
137
has_many :moons
138
- has_one :planet_type
138
+ belongs_to :planet_type
139
139
140
140
has_and_belongs_to_many :tags , join_table : :planets_tags
141
141
end
@@ -452,7 +452,7 @@ class PropertyResource < JSONAPI::Resource
452
452
end
453
453
454
454
class PlanetTypeResource < JSONAPI ::Resource
455
- attribute :name
455
+ attributes :id , :name
456
456
has_many :planets
457
457
end
458
458
Original file line number Diff line number Diff line change @@ -549,4 +549,50 @@ def test_serializer_empty_links_null_and_array
549
549
assert_match /\" planetType\" :null/ , json
550
550
assert_match /\" moons\" :\[ \] / , json
551
551
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
552
598
end
You can’t perform that action at this time.
0 commit comments