Skip to content

Fix polymorphic type setter#882

Merged
barelyknown merged 2 commits intoJSONAPI-Resources:masterfrom
Exelord:fix-polymorphic-type
Oct 24, 2016
Merged

Fix polymorphic type setter#882
barelyknown merged 2 commits intoJSONAPI-Resources:masterfrom
Exelord:fix-polymorphic-type

Conversation

@Exelord
Copy link
Copy Markdown
Contributor

@Exelord Exelord commented Oct 19, 2016

Hey @lgebhardt!
We encounter a problem associated with the polymorphic relation. Here is an example in code:

Setup

Models:

class Conversation < ActiveRecord::Base
  has_many :topics
end

class Account::Template < ActiveRecord::Base
  has_many :topics
end

class Topic < ActiveRecord::Base
  belongs_to :document, polymorphic: true
end

Resources:

class Template < JSONAPI::Resource
  model_name 'Account::Template'
  has_many :topics
end

class Topic < JSONAPI::Resource
  has_one :document, polymorphic: true
end

Usage

Request: [ POST ] /topics

{
    "data": {
        "attributes": {
            "name": "Topic name",
        },
        "relationships": {
            "document": {
                "data": {
                    "type": "templates",
                    "id": "1"
                }
            },
        },
        "type": "topics"
    }
}

Problem

Newly created topic has the wrong name of document_type filed.
After typing topic.document_type it was Templates but in fact, the polymorphic type should be taken from a model name and it should look like Account::Template because it's the real name of the resource's model's class name.

Solution

I overwrite a method which assigns polymorphic type, and I created a method which looking for a real model class name of given relation's key_type.

I hope it will help :)

@barelyknown
Copy link
Copy Markdown
Collaborator

Nice catch. Can you add a test that fails without this fix and passes with it?

@Exelord
Copy link
Copy Markdown
Contributor Author

Exelord commented Oct 24, 2016

@barelyknown I added a test. I'm not familiar with the rails test framework (I used to use rspec) so feedback is welcome.

@barelyknown
Copy link
Copy Markdown
Collaborator

Nice and simple - thanks!

@barelyknown barelyknown merged commit 81ac803 into JSONAPI-Resources:master Oct 24, 2016
@Exelord Exelord deleted the fix-polymorphic-type branch October 24, 2016 14:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants