我怎样才能返回与葡萄实体和扬鞭的多态性数据?

问题描述 投票:0回答:1

我有一个多态性标记,并希望通过这个标签来搜索暧昧的项目。 我如何与葡萄实体返回此?

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

我需要定义taggable的实体,露出一扬鞭又名OpenAPI的接口。

ruby-on-rails swagger grape grape-entity
1个回答
0
投票

在这种情况下,我们可以使用:

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
© www.soinside.com 2019 - 2024. All rights reserved.