Question

I have spent the past few hours trying to figure out what I am doing wrong, but I cannot come to a solution. Simply put, I am trying to populate a select box with data from a table called 'semesters'. (I've seen tons of questions regarding this on SO, but I cannot get them to work with my app).

Here's what I have:

Courses Controller

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

View

#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 %>

I was hoping it would output:

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

But instead, I am getting the error:

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

      undefined method `map' for nil:NilClass

Line #32 corresponds to my form helper select.

Any help on this would be great!

Was it helpful?

Solution

You should set your @semesters variable in controller:

def new
  @semesters = Semester.all
end

The error occurs because unset instance variable is evaluated to nil, so you try to call map method on nil object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top