How can I return polymorphic data with Grape Enttity and Swagger?

278 Views Asked by At

I have a polymorphic tag and want to search ambigous items by this tag.
How can I return this whith Grape Entity?

class Tag < ActiveRecord::Base
  belongs_to :taggable, polymorphic: true
end

class Article < ActiveRecord::Base
  has_many :tags, as: :taggable
end

class Post < ActiveRecord::Base
  has_many :tags, as: :taggable
end

module Api
  module Entities
    class Tag < Grape::Entity
      expose :lable
      expose :taggable # HELP: , using Api::Entities::<polymorphic>
    end
end

I need to define the Entity of taggable to expose a Swagger aka OpenAPI interface.

1

There are 1 best solutions below

0
thanhnha1103 On

In this case we can use:

module Api
  module Entities
    class Tag < Grape::Entity
      expose :lable
      expose :taggable do |tabgable, options|
        if tabgable.is_a?(Article)
          API::Entities::Article.represent tabgable, options
        elsif tabgable.is_a?(Post)
          API::Entities::Post.represent tabgable, options
        end
      end
    end
  end
end