collection_select不保存/错误

时间:2011-08-07 15:52:01

标签: ruby-on-rails collections

我正在尝试创建一个新的课程创建表单,下拉菜单从教师的表格中选择一个教学。

当我将下面的内容放入我的新课程表单视图时,我收到此错误:

  

当你没想到它时,你有一个零对象!

<%= collection_select(:Teacher, :id, @teachers, :id, :name, options = {:prompt => "Select a Teacher"}) %>

如果我把

<%= collection_select(:Teacher, :id, Teacher.find(:all), :id, :name, options = {:prompt => "Select a Teacher"}) %>

它使用正确的下拉信息创建表单,但之后它将无法保存。

我的课程控制器创建方法看起来像这样

 def create
@course = Course.new(params[:course])

respond_to do |format|
  if @course.save
    format.html { redirect_to(@course, :notice => 'Course was successfully created.') }
    format.xml  { render :xml => @course, :status => :created, :location => @course }
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @course.errors, :status => :unprocessable_entity }
  end

1 个答案:

答案 0 :(得分:2)

重写像这样的新动作



    def new
         @course = Course.new
         @teachers = Teachers.all

         respond_to do |format|
           format.html # new.html.erb
           format.xml  { render :xml => @course }
         end
      end

之后

<%= collection_select(:Teacher, :id, @teachers, :id, :name, options = {:prompt => "Select a Teacher"}) %>

应该有效