ruby-on-rails - 如何使用国家宝石生成国家名称列表作为 JSON
问题描述
我正在构建一个 rails api,需要将所有国家/地区发送为JSON
using 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
]
我希望我可以使用序列化程序,以便将名称翻译成不同的语言
解决方案
根据您的评论,序列化程序配置为与 Rails 模型一起使用,并且您的数据来自countries
gem。
如果您只需要 name 属性,您可以执行以下操作:
def index
countries = Country.all
render json: { countries: ISO3166::Country.all.map(&:name) }
end
推荐阅读
- r - 为 R 安装拨浪鼓时遇到问题
- java - 如何使用 view.GONE 处理 ConstraintLayout 水平和垂直
- oauth - 如何为 azure vm 生成 OAuth
- c++ - 函数没有返回任何值 | C++
- javascript - 仅使用已分配关键帧的纯 CSS 在元素上触发动画
- django - /create_order/ __str__ 处的 TypeError 返回非字符串(NoneType 类型)
- java - 使用Java从JSON文件中删除一定范围内的键/值对
- javascript - Node JS Axios 分离数据
- python - 有没有办法为 tkinter 设置默认按钮颜色(点击时)?
- javascript - 在散景图数据更改上添加动画(更慢、更平滑的更改)