如何使用国家 gem 生成国家名称列表 JSON

How to use countries gem to generate a list of country names as JSON

我正在构建 rails api 并且需要使用 AMS 将所有国家发送为 JSON。我能够获取国家/地区,但无法将其作为 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
]

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

根据您的评论,序列化器配置为与 Rails 模型一起使用,并且您的数据来自 countries gem.

如果你只需要名称属性,你可以这样做:

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