将别名应用于葡萄实体中的循环



我想获得以下JSON。

[{"Product":{"CountryName":4848, }},{"Product":{"CountryName":700}]

module API
  module Entities
    class Example < Grape::Entity
      expose(:product) do
        expose(:country_name) do |product, options|
          product.country.name
        end
      end
    end
  end
end

参数是产品和名称。我想返回产品名称。

如何将别名应用于葡萄实体框架中的循环元素?

  • Product属性:使用'Product'字符串代替:product符号,
  • CountryName属性:您需要在实体中创建一种方法,该方法将返回 product.country.name并将其暴露在实体中。然后,使用一个别名,以便按预期的是CountryName(如果需要的话,您可以看到有关别名的葡萄 - 实体文档(。

在您的情况下,这将给出:

module API
  module Entities
    class Product < Grape::Entity
      expose 'Product' do
        # You expose the result of the country_name method, 
        # and use an alias to customise the attribute name
        expose :country_name, as: 'CountryName'
      end
      private
      # Method names are generally snake_case in ruby, so it feels
      # more natural to use a snake_case method name and alias it
      def country_name
        object.country.name
      end
    end
  end
end

在您的终点中,您指定必须使用来序列化产品实例的实体。在我的示例中,您可能已经注意到我将实体重命名为Product的自由,这将使我们在端点:

# /products endpoint
resources :products do
  get '/' do
    present Product.all, with: API::Entities::Product
  end
end

应该为您提供这种输出,如预期:

[
    { "Product": { "CountryName": "test 1" } },
    { "Product": { "CountryName": "test 2" } }
]

最新更新