Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/svn/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails RubyonRails:未定义的方法&x27;地图';对于#<;字符串>;_Ruby On Rails_Json_Ruby_Forms - Fatal编程技术网

Ruby on rails RubyonRails:未定义的方法&x27;地图';对于#<;字符串>;

Ruby on rails RubyonRails:未定义的方法&x27;地图';对于#<;字符串>;,ruby-on-rails,json,ruby,forms,Ruby On Rails,Json,Ruby,Forms,我试图使用and标记创建rails表单,但我想用json文件生成选项,因为我想要所有国家/地区。 但我有一个错误: undefined method `map' for #<String:0x007f871472e9b0> 这是我的帖子(u controller.rb): def create countries_for_select @post = Post.new(posts_params) @post.user = current_user

我试图使用and标记创建rails表单,但我想用json文件生成选项,因为我想要所有国家/地区。 但我有一个错误:

undefined method `map' for #<String:0x007f871472e9b0> 
这是我的帖子(u 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
以下是my_form.html.erb文件中的行:

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

所以我不明白为什么它不起作用, 有人能帮我吗


谢谢大家!

删除
至_json

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

Rails.root
有一个方法
join

Rails.root.join('app', 'helpers', 'countries.json')

我认为
file=file.read(file.join(Rails.root,'app','helpers','countries.json')).to_json
行实际上并没有返回json对象,只是返回一个字符串。您是否尝试过打印
国家/地区

它也可能与post有关。

您不需要
。在这里使用json

file = File.read(File.join(Rails.root, 'app', 'helpers', 'countries.json')).to_json
countries = JSON.parse(file)
.to_json
是jsonifig对象(从复杂对象生成json字符串)

当它应用于字符串时,它返回一个包含字符串的字符串

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

File.read
已经返回了有效的json字符串(或者我们假设是这样),您可以稍后对其进行
json.parse
。但是,当您再次对它进行jsonify时,它会变成另一个json对象:一个字符串(该字符串又包含一些json)。这就是导致错误的原因:字符串没有方法
.map

,我要详细说明一下。@SergioTulentsev我的英语或其他任何东西?这个更好:)@AntoninMrchd您的json文件无效。在这里检查您的文件@AntoninMrchd:根据json规范,键必须是双引号。还有字符串。这样递归序列化程序就可以工作了,我想:)@code>nil.to_json==“null”。
"{foo: 1}".to_json # => "\"{foo: 1}\""