Antonin Mrchd Antonin Mrchd - 19 days ago 5
JSON Question

Ruby on rails and JSON to create Select form

I want to create a form like that :

<select>
<option>
</select>


with ruby on rails, but it is for countries (and there is a lot of countries in the world haha), so I don't want to write everyone on my view, so I want to put a JSON file with all countries, and get theme in my option items ( with each method maybe )

I don't know where I have to put my json file in my rails app and how call it in my view,

does someone could help me ?

Answer

The easiest location to put your JSON file is in the same directory as your controllers -- although doing this kind of thing repeatedly will quickly make a mess out of your controllers folder.

Once you've done that you can read it from your controller like this:

var file = File.read('./countries.json')
var countries = JSON.parse(file)

and then map countries to the data type that options_for_select expects.

Once you have that working, I'd recommend making a helper that knows how to read the json file, cache it's data, and return it. Store the json file in the same directory as the helper. Reference the helper in your controller.

Also note: the JSON gem is required for this.