0

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 !

3 Answers 3

3

Remove to_json:

 File.read(File.join(Rails.root, 'app', 'helpers', 'countries.json')).to_json
                                                                     ^^^^^^^^^

A little tip:

Rails.root has a method join:

Rails.root.join('app', 'helpers', 'countries.json')
Sign up to request clarification or add additional context in comments.

12 Comments

I'd elaborate on that.
@SergioTulentsev my english or anything else?
This one is better :)
@AntoninMrchd your json file is not valid. Check your file here jsonlint.com
@AntoninMrchd: according to json spec, keys must be double-quoted. And strings too.
|
2

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.

Comments

2

You don't need the .to_json here

file = File.read(File.join(Rails.root, 'app', 'helpers', 'countries.json')).to_json
countries = JSON.parse(file)

.to_json is jsonifying objects (producing a json string from a complex object).

When it is applied to strings, it returns a string which contains a string.

"{foo: 1}".to_json # => "\"{foo: 1}\""

File.read already returns you valid json string (or so we assume), which you can later JSON.parse. But when you jsonify it one more time, it becomes another json object: a string (which, in turn, contains some json). This is what causes your error: strings don't have method .map.

2 Comments

@Зелёный: so that recursive serializers can work, I think :)
@Зелёный the reason is the same as nil.to_json == 'null'.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.