Jsonapi-resources: How to get Single Table Inheritance (STI) models completely grouped under parent endpoint?

Created on 16 Feb 2016  路  3Comments  路  Source: cerebris/jsonapi-resources

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?

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:

class Api::AnimalResource < JSONAPI::Resource
  model_hint model: Cat, resource: :animal
  model_hint model: Dog, resource: :animal
end

All 3 comments

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
Was this page helpful?
0 / 5 - 0 ratings

Related issues

CodingItWrong picture CodingItWrong  路  3Comments

mrcasals picture mrcasals  路  4Comments

edipox picture edipox  路  4Comments

achan picture achan  路  6Comments

thedeeno picture thedeeno  路  6Comments