2013-07-29 43 views
1

我花了幾個小時試圖弄清楚我做錯了什麼,但我無法找到解決方案。簡而言之,我試圖用一個名爲'學期'的表填充選擇框。 (我已經看到很多關於這個的問題,但我無法讓他們與我的應用程序一起工作)。Ruby on Rails - 未定義的方法`map'for nil:NilClass

這是我有:

課程控制器

class CoursesController < ApplicationController 
    def create 
    @semesters = Semester.all() 
    @course = Course.new(params[:course]) 
    # Save the object 
    if @course.save 
     flash[:notice] = "Course created." 
     redirect_to(:action => 'list') 
    else 
     # If save fails, redisplay the form so user can fix problems 
     render('new') 
    end 
    end 
end 

查看

#views/courses/new.html.erb 
<%= form_for(:course, :url => {:action => 'create'}) do |f| %> 
    <%= f.select(:semester, @semesters.map { |s| [ s.name, s.id ] }) %> 
    <%= submit_tag("Create Course") %> 
<% end %> 

我希望它會輸出:

<select> 
    <option id="1">Spring 2013</option> 
    <option id="2">Fall 2013</option> 
    </select> 

但是,相反,我得到錯誤:

views/courses/new.html.erb where line #32 raised: 

     undefined method `map' for nil:NilClass 

行#32對應於我的表單助手選擇。

任何幫助,這將是偉大的!

+0

錯誤消息說明了這一切,'@ semesters'是'nil'。 –

+0

你可以發佈''''''''課程控制器''的行動嗎? – daniloisr

+1

也發佈'新'行動。我的猜測是,你沒有在這個行動中定義@學期。 –

回答

6

你應該設置你@semesters變量控制器:發生

def new 
    @semesters = Semester.all 
end 

的錯誤,因爲未設置實例變量進行評估,以nil,所以你嘗試調用map方法上nil對象。

+0

你說得對。我不小心將它設置在「創建」動作中,而不是「新」動作。謝謝。 – Dodinas

相關問題