From e351a74069a3de69c457603b57b2751391bdf572 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maciej=20Kwa=C5=9Bniak?= Date: Wed, 19 Oct 2016 11:22:08 +0200 Subject: [PATCH 1/2] Fix polymorphic type setter --- lib/jsonapi/resource.rb | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/jsonapi/resource.rb b/lib/jsonapi/resource.rb index 25697c536..14c34d417 100644 --- a/lib/jsonapi/resource.rb +++ b/lib/jsonapi/resource.rb @@ -324,7 +324,7 @@ def _replace_polymorphic_to_one_link(relationship_type, key_value, key_type, opt relationship = self.class._relationships[relationship_type.to_sym] _model.public_send("#{relationship.foreign_key}=", key_value) - _model.public_send("#{relationship.polymorphic_type}=", key_type.to_s.classify) + _model.public_send("#{relationship.polymorphic_type}=", _model_class_name(key_type)) @save_needed = true @@ -404,6 +404,12 @@ def _replace_fields(field_data) :completed end + def _model_class_name(key_type) + type_class_name = key_type.to_s.classify + resource = self.class.resource_for(type_class_name) + resource ? resource._model_name.to_s : type_class_name + end + class << self def inherited(subclass) subclass.abstract(false) From 4e8110e9a120c2abdc2f397022e40a3946fa6b17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maciej=20Kwa=C5=9Bniak?= Date: Mon, 24 Oct 2016 11:44:20 +0200 Subject: [PATCH 2/2] Add test --- test/fixtures/active_record.rb | 8 ++++++++ test/unit/resource/resource_test.rb | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/test/fixtures/active_record.rb b/test/fixtures/active_record.rb index 284368777..778c72538 100644 --- a/test/fixtures/active_record.rb +++ b/test/fixtures/active_record.rb @@ -572,6 +572,9 @@ class Document < ActiveRecord::Base has_many :pictures, as: :imageable end +class Document::Topic < Document +end + class Product < ActiveRecord::Base has_one :picture, as: :imageable end @@ -1209,6 +1212,11 @@ class DocumentResource < JSONAPI::Resource has_many :pictures end +class TopicResource < JSONAPI::Resource + model_name 'Document::Topic' + has_many :pictures +end + class ProductResource < JSONAPI::Resource attribute :name has_one :picture, always_include_linkage_data: true diff --git a/test/unit/resource/resource_test.rb b/test/unit/resource/resource_test.rb index 2fd8b68f8..4c8e94daa 100644 --- a/test/unit/resource/resource_test.rb +++ b/test/unit/resource/resource_test.rb @@ -205,6 +205,14 @@ def test_class_relationships assert_equal(relationships.size, 2) end + def test_replace_polymorphic_to_one_link + picture_resource = PictureResource.find_by_key(Picture.first) + picture_resource.replace_polymorphic_to_one_link('imageable', '9', 'Topic') + + assert Picture.first.imageable_id == 9 + assert Picture.first.imageable_type == Document::Topic.to_s + end + def test_duplicate_relationship_name assert_output nil, "[DUPLICATE RELATIONSHIP] `mother` has already been defined in CatResource.\n" do CatResource.instance_eval do