active_model_serializers: JSONAPI - Wrong "type" for belongs_to polymorphic relationships
Expected behavior vs actual behavior
For JSONAPI, after this pr is merged: #1857, type
parameter returns the relation type, instead of resource type.
Steps to reproduce
serializer:
class CommentSerializer < ActiveModel::Serializer
# ....
belongs_to :commentable # post, image etc.
end
request:
/comments?include=commentable
expected:
//...
"relationships": {
"commentable": {
"data": {
"id": "1",
"type": "posts"
}
}
}
//...
result:
//...
"relationships": {
"commentable": {
"data": {
"id": "1",
"type": "commentables"
}
}
}
//...
Environment
ActiveModelSerializers Version, after this: #1857
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 8
- Comments: 23 (8 by maintainers)
This do not solve the problem but as a workaround in your application you could change your
belong_to :field, polymorphic: true
tohas_one :field, polymorphic: true
and the type returned will be ok.I tried to solve the problem… it seems like we should access attribute #{name}_type on polymorphic relationships on parent object, but on ::ActiveModel::Serializer::Reflection initialize method parent object is not initialized.
I cannot envision a single way OJ might change this behavior 🤔
@andyhite
More of just that maintainers tend to scratch their own itch, and I’ve been busy doing other things and no one has fixed it yet. Maybe part of the problem is ego because I worked really hard on the code in between 0.10.5 and 0.10.6 and don’t really want to yank it. I’d rather fix it. But I need help.
@bf4 sorry, I didn’t mean to come across as rude as I did. It’s just a pretty big issue and makes 0.10.6 unusable for a lot of people. I understand you worked hard on the code between 0.10.5 and 0.10.6, which should be good reason to fix it so we can all reap the benefits of 0.10.6, haha.
I spent about a day trying to figure it out, and came up with the band-aid I mentioned in a comment back in June (which I’m unfortunately running in production via my fork), but it unfortunately isn’t a complete solution and breaks something that I’m not currently using (can’t remember what, off the top of my head) - so it’s fine for my case, but not something that can be merged upstream.
Having same issue. Downgraded to 0.10.5
having same issue, passing custom
type: :versions
but it still as model.table_nameMy temporary hack to fix this is the following:
I haven’t tested anything other than my case though, so I’m not comfortable pull requesting it yet.