Skip to content

Commit a4f5a74

Browse files
BrunoChauvetchingor13
authored andcommitted
Fix initializing resource including relationships (#263)
* fix initializing resource including relationships * add test for resource instantiation with associations
1 parent 1e87d58 commit a4f5a74

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

lib/json_api_client/resource.rb

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -305,15 +305,17 @@ def initialize(params = {})
305305
@persisted = nil
306306
self.links = self.class.linker.new(params.delete("links") || {})
307307
self.relationships = self.class.relationship_linker.new(self.class, params.delete("relationships") || {})
308-
self.class.associations.each do |association|
309-
if params.has_key?(association.attr_name.to_s)
310-
set_attribute(association.attr_name, association.parse(params[association.attr_name.to_s]))
311-
end
312-
end
313308
self.attributes = params.merge(self.class.default_attributes)
309+
314310
self.class.schema.each_property do |property|
315311
attributes[property.name] = property.default unless attributes.has_key?(property.name) || property.default.nil?
316312
end
313+
314+
self.class.associations.each do |association|
315+
if params.has_key?(association.attr_name.to_s)
316+
set_attribute(association.attr_name, params[association.attr_name.to_s])
317+
end
318+
end
317319
end
318320

319321
# Set the current attributes and try to save them

test/unit/resource_test.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,4 +82,11 @@ def test_formatted_key_accessors
8282
assert_equal("baz", article[:"foo-bar"])
8383
end
8484
end
85+
86+
def test_associations_as_params
87+
article = Article.new(foo: 'bar', 'author' => {'type' => 'authors', 'id' => 1})
88+
assert_equal(article.foo, 'bar')
89+
assert_equal(article.attributes['author']['type'], 'authors')
90+
assert_equal(article.attributes['author']['id'], 1)
91+
end
8592
end

0 commit comments

Comments
 (0)