1

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!

3
  • The error message says it all, @semesters is nil. Commented Jul 29, 2013 at 21:10
  • Can you post your edit action of CoursesController? Commented Jul 29, 2013 at 21:14
  • 1
    Also post the new action. My guess is that you're not defining @semesters in that action. Commented Jul 29, 2013 at 21:17

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You're right. I was accidentally setting it in the create action, not the new action. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.