【问题标题】:Ruby on rails errors undefined method `map' for nil:NilClassRuby on rails 错误为 nil:NilClass 的未定义方法“map”
【发布时间】:2016-04-05 08:01:32
【问题描述】:

以下是从我的文件 /home/divya/climb/project1/app/views/cities/new.html.erb 中提取的代码,其中第 5 行引发了此错误:

nil:NilClass 的未定义方法 `map'

提取的源代码(第 5 行附近):

2: <%= form_for(@city) do |f| %>
3: <%= f.label :country_id %><br />
4: 
5: <%= collection_select(:city, :country_id, @countries, :id, :country_name, {:prompt => false}) %>
6: <%= render 'form' %>
7: 
8: <%= link_to 'Back', cities_path %>

Rails.root: /home/divya/climb/project

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    显然你没有在控制器中设置你的@countries实例变量,所以它是nilmap 方法在 @countries 内部由 ActionView 调用(严格来说,通过 options_from_collection_for_select 方法)。

    您应该在控制器中设置@countries,使用:

    @countries = Country.all
    

    或者直接在视图中调用:

    <%= collection_select(:city, :country_id, Country.all, :id, :country_name, { :prompt => false }) %>
    

    【讨论】:

      【解决方案2】:

      改变

      <%= collection_select(:city, :country_id, @countries, :id, :country_name, {:prompt => false}) %>
      

      <%= collection_select(:city, :country_id, Country.all, :id, :country_name, {:prompt => false}) %>
      

      【讨论】:

        【解决方案3】:

        仅在控制器中使用全局变量 $countries=Country.all 更改此变量,而您的视图使用此变量。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-03-04
          • 1970-01-01
          • 1970-01-01
          • 2022-11-21
          • 1970-01-01
          • 2012-09-24
          • 1970-01-01
          相关资源
          最近更新 更多