Skip to content

Commit 75229fd

Browse files
authored
Dev (#232)
* Remove extra 'class MovieSerializer' from an example in the README * Fix serialization for nested nil includes with block
1 parent 81375cf commit 75229fd

4 files changed

Lines changed: 26 additions & 3 deletions

File tree

README.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,6 @@ block you opt-in to using params by adding it as a block parameter.
284284

285285
```ruby
286286
class MovieSerializer
287-
class MovieSerializer
288287
include FastJsonapi::ObjectSerializer
289288

290289
attributes :name, :year

lib/fast_jsonapi/serialization_core.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ def fetch_id(record, relationship, params)
182182
object = relationship[:object_block].call(record, params)
183183

184184
return object.map(&:id) if object.respond_to? :map
185-
return object.id
185+
return object.try(:id)
186186
end
187187

188188
record.public_send(relationship[:id_method_name])

spec/lib/object_serializer_spec.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,13 @@
9797
expect(serializable_hash['data']['relationships']['owner']['data']).to be nil
9898
end
9999

100+
it 'returns correct json when belongs_to returns nil and there is a block for the relationship' do
101+
movie.owner_id = nil
102+
json = MovieSerializer.new(movie, {include: [:owner]}).serialized_json
103+
serializable_hash = JSON.parse(json)
104+
expect(serializable_hash['data']['relationships']['owner']['data']).to be nil
105+
end
106+
100107
it 'returns correct json when has_one returns nil' do
101108
supplier.account_id = nil
102109
json = SupplierSerializer.new(supplier).serialized_json

spec/shared/contexts/movie_context.rb

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,13 @@ def advertising_campaign
4343
ac
4444
end
4545

46+
def owner
47+
return unless owner_id
48+
ow = Owner.new
49+
ow.id = owner_id
50+
ow
51+
end
52+
4653
def cache_key
4754
"#{id}"
4855
end
@@ -146,14 +153,24 @@ class Account
146153
attr_accessor :id
147154
end
148155

156+
class Owner
157+
attr_accessor :id
158+
end
159+
160+
class OwnerSerializer
161+
include FastJsonapi::ObjectSerializer
162+
end
163+
149164
# serializers
150165
class MovieSerializer
151166
include FastJsonapi::ObjectSerializer
152167
set_type :movie
153168
# director attr is not mentioned intentionally
154169
attributes :name, :release_year
155170
has_many :actors
156-
belongs_to :owner, record_type: :user
171+
belongs_to :owner, record_type: :user do |object, params|
172+
object.owner
173+
end
157174
belongs_to :movie_type
158175
has_one :advertising_campaign
159176
end

0 commit comments

Comments
 (0)