Skip to content

Commit 273b7e7

Browse files
ssendevbf4
authored andcommitted
belongs_to causes unnecessary db hit
1 parent 0f59d64 commit 273b7e7

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

test/serializers/associations_test.rb

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,34 @@ def test_associations_custom_keys
137137
assert expected_association_keys.include? :site
138138
end
139139

140+
class BelongsToBlogModel < ::Model
141+
attributes :id, :title
142+
associations :blog
143+
end
144+
class BelongsToBlogModelSerializer < ActiveModel::Serializer
145+
type :posts
146+
belongs_to :blog
147+
end
148+
149+
def test_belongs_to_doesnt_load_record
150+
attributes = { id: 1, title: 'Belongs to Blog', blog: Blog.new(id: 5) }
151+
post = BelongsToBlogModel.new(attributes)
152+
class << post
153+
def blog
154+
fail 'should use blog_id'
155+
end
156+
157+
def blog_id
158+
5
159+
end
160+
end
161+
162+
actual = serializable(post, adapter: :json_api, serializer: BelongsToBlogModelSerializer).as_json
163+
expected = { data: { id: '1', type: 'posts', relationships: { blog: { data: { id: '5', type: 'blogs' } } } } }
164+
165+
assert_equal expected, actual
166+
end
167+
140168
class InlineAssociationTestPostSerializer < ActiveModel::Serializer
141169
has_many :comments
142170
has_many :comments, key: :last_comments do

0 commit comments

Comments
 (0)