Antonin Mrchd Antonin Mrchd - 18 days ago 5
JSON Question

Ruby on rails : undefined method 'map' for #<String>

I am trying to create a rails form using and tag, but I want to generate options with a json file, because I want all the countries.
But I have this error :

undefined method `map' for #<String:0x007f871472e9b0>


Here is my application_helper.rb :

module ApplicationHelper
def countries_for_select
file = File.read(File.join(Rails.root, 'app', 'helpers', 'countries.json')).to_json
countries = JSON.parse(file)
countries.map {|c| [ c['country']['name'], v['country']['code'] ] }
end
end


Here is my posts_controller.rb :

def create
countries_for_select
@post = Post.new(posts_params)
@post.user = current_user
options_for_countries
if @post.save
flash[:success] = "Your post have been published"
redirect_to post_show_path
else
render 'new'
end
end


Here is the line in my _form.html.erb file :

<%= select_tag(:country, countries_for_select) %>


So I don't understand why it doesn't work,
Does someone could help me ?

Thank you !

Answer

I think the file = File.read(File.join(Rails.root, 'app', 'helpers', 'countries.json')).to_json line does not really return a JSON object, just a String. Have you tried printing countries? It could have something to do with this post too.