collection_select 未保存/出错

发布于 2024-11-28 17:31:36 字数 952 浏览 0 评论 0原文

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

当我将以下内容放入新课程表单视图中时,出现此错误:

当你没有预料到时,你得到了一个 nil 对象!

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

I'm trying to create a new course create form with a drop down to select a teach from the teacher's table.

When I put the below in my new course form view I get this error:

You have a nil object when you didn't expect it!

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

if I put

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

it creates the form with the correct drop down info but then it won't save.

My course controller create method looks like this

 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

胡大本事 2024-12-05 17:31:36

像这样重写新操作

    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"}) %>

应该可以工作

Rewrite new action like this


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

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

After that

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

should work

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文