Hello,
It might sound like a regression (I found issues that seem to describe the behaviour I'm looking for as a "bug", and "fixed" it), but I'll ask about it anyway. I have an ActiveRecord::Model with STI (and a type attribute). Say it's an Animal model, with a complete zoo of types (Cat, Dog, what have you).
I would rather not have to declare a JR resource and controller for each type, and would like only one /animals endpoint in my API, to handle all operations (index + CRUD). I'd also prefer the resource type in the API's responses to always be animals, and have a simple type attribute that will expose what kind of animal we have.
Is there a way to do this?
I'll answer to myself, although I have no idea if this is good practice or not (kinda looks gross to me).
class Api::AnimalResource < JSONAPI::Resource
include Api::CentralizedSti
end
module Api::CentralizedSti
extend ActiveSupport::Concern
included do
attribute :type
end
module ClassMethods
def resource_type_for(model)
model = model.becomes(_model_class) if model.is_a?(_model_class)
super(model)
end
private
def check_reserved_attribute_name(name)
# Do not warn about NAME COLLISION on the type attribute.
end
end
end
I'm also interested to know the solution.
The model_hint method you can call seems like a nice way to have one resource for STI.
So for your example something like:
class Api::AnimalResource < JSONAPI::Resource
model_hint model: Cat, resource: :animal
model_hint model: Dog, resource: :animal
end
Most helpful comment
The model_hint method you can call seems like a nice way to have one resource for STI.
So for your example something like: