首页 > 解决方案 > 如何使用国家宝石生成国家名称列表作为 JSON

问题描述

我正在构建一个 rails api,需要将所有国家/地区发送为JSONusing AMS. 我能够获取国家/地区,但无法将其发送为JSON. 我得到错误:undefined method [] for nil class

def index
  countries = Country.all
  render json: countries, serializer: CountrySerializer
end
class CountrySerializer < ActiveModel::Serializer 
  attributes(:name)
end

我期望JSON响应是一个数组

[
 England,
 Netherland
]

我希望我可以使用序列化程序,以便将名称翻译成不同的语言

标签: ruby-on-railsrubygemsruby-on-rails-5

解决方案


根据您的评论,序列化程序配置为与 Rails 模型一起使用,并且您的数据来自countriesgem。

如果您只需要 name 属性,您可以执行以下操作:

def index
  countries = Country.all
  render json: { countries: ISO3166::Country.all.map(&:name) }
end

推荐阅读