TLDR ;Есть ли более простой способ получить тип ресурса, определенный в сериализаторе?
Я использую гем active_model_serializers
, и он настроен на использование адаптера :json_api
.
Вот как выглядит мой класс сериализатора:
class ProductCategorySerializer < ActiveModel::Serializer
type :product_categories # the type is defined here
attributes :title
has_many :products do
account = scope.instance_variable_get(:@account)
# getting the type is a hassle
serializer = ActiveModelSerializers::SerializableResource.new(self).serializer_instance
category_type = ActiveModelSerializers::Adapter::JsonApi::ResourceIdentifier.type_for(serializer, serializer._type)
link :related, Rails.application.routes.url_helpers.products_api_v1_account_product_categories_path(account_id: account.id, category_type: object.type, category_id: object.id, format: "json")
end
end
Вот модель.Это довольно просто и не так важно для вопроса.
class ProductCategory
include ActiveModel::Model
alias :read_attribute_for_serialization :send
attr_accessor :title
attr_accessor :products
end
Итак, сейчас, чтобы получить type
, я должен использовать эти 2 строки кода.Даже если я в сериализаторе, который определяет type
.Похоже, это можно сделать менее сложным способом, не так ли?
serializer = ActiveModelSerializers::SerializableResource.new(self).serializer_instance
category_type = ActiveModelSerializers::Adapter::JsonApi::ResourceIdentifier.type_for(serializer, serializer._type)