我正在使用葡萄(0.14.0)和葡萄实体(0.5.0)在我的Rails(4.2.5)应用程序中创建一个XML API。每当我在 Grape::Entity 类中指定显式根元素时,XML 响应就会被包装在不需要的根元素<hash>
中。我怎样才能摆脱它?
示例代码
# app/models/partner.rb
class Partner < ActiveRecord::Base
# company :string
# name :string
# secret :string
end
# app/api/partners.rb
class Partners < Grape::API
version 'v1', using: :path
prefix :api
format :xml
resource :partners do
get do
present Partner.all, with: PartnerEntity
end
end
end
# app/api/partner_entity.rb
class PartnerEntity < Grape::Entity
root 'partners', 'partner'
expose :company
expose :name
expose :id
end
# Create a partner
Partner.create!(name: 'A Name', company: 'A Company', secret: 'A secret')
结果
# GET /api/v1/partners.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<hash>
<partners type="array">
<partner>
<company>A Company</company>
<name>A Name</name>
<id type="integer">1</id>
</partner>
</partners>
</hash>
在 PartnerEntity 中没有根的结果
# GET /api/v1/partners.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<partner-entities type="array">
<partner-entity>
<company>A Company</company>
<name>A Name</name>
<id type="integer">2</id>
</partner-entity>
</partner-entities>
因为我需要明确命名我的根元素,所以我不能没有根。