2013-08-12 62 views
1

下面是代碼從我的文件/home/divya/climb/project1/app/views/cities/new.html.erb中提取出來,其中第5行提出了這個錯誤:Ruby on rails錯誤undefined方法`map'for nil:NilClass

undefined method `map' for nil:NilClass

提取的源(左右線#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 

回答

7

顯然你沒有設置控制器在@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}) %> 
0

只在控制器中更改此變量使用全局變量$ countries = Country.all並且您的視圖使用此變量。