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

I am building a rails api and need to send all country as JSON using AMS. I am able to fetch the countries but not able to send it as JSON. I get the error: undefined method [] for nil class

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

I am expecting the JSON response to be an array like

[ England, Netherland ] 

I was hoping I could make use of serializers so I could translate the names in different languages

2

1 Answer

Per your comment, serializers are configured to work with Rails models, and your data is coming from the countries gem.

If all you need is the name attribute you can do:

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like