I would like to get the following 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
The parameters are product and name. I would like to return Product, ProductName.
How to apply alias for looping elements in grape entity framework?
Product
attribute : use a 'Product'
string instead of the :product
symbol,CountryName
attribute : you need to create a method in your entity that will return product.country.name
and expose it in your entity. And then, use an alias so that the key will be CountryName
as expected (you can see grape-entity documentation about aliases if need be).In your case, this would give :
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
And in your endpoint, you specify the entity that must be used to serialize the Products instances. In my example, you may have noticed that I took the liberty of renaming the entity to Product
, which would give us in the endpoint:
# /products endpoint
resources :products do
get '/' do
present Product.all, with: API::Entities::Product
end
end
Which should get you this kind of output, as expected:
[
{ "Product": { "CountryName": "test 1" } },
{ "Product": { "CountryName": "test 2" } }
]