【问题标题】:How to use countries gem to generate a list of country names as JSON如何使用国家宝石生成国家名称列表作为 JSON
【发布时间】:2019-07-17 14:20:53
【问题描述】:

我正在构建一个 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
]

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

【问题讨论】:

  • 请发布您的CountrySerializer的代码
  • 添加了序列化程序,但直到序列化程序才到达

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


【解决方案1】:

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

如果您只需要 name 属性即可:

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

【讨论】:

  • def index countries = Country.all.map(&amp;:name) render json: countries.to_json end 我已经按照您的建议完成了,但设置序列化程序不起作用。我收到一个错误,例如未定义的方法模型名称。序列化程序是否特定于模型,因为我的数据库中没有国家/地区表
  • 好点。我用可能对您有用的解决方案更新了答案。您可以编辑您的问题以显示您尝试从序列化程序获取的输出示例吗?
  • 我已经用输出更新了我的问题。并感谢您的帮助
  • 没问题。啊,我明白了;我想我知道你在找什么。我已经更新了答案。
猜你喜欢
  • 1970-01-01
  • 2014-08-04
  • 2014-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多