rails form_for从不调用create controller动作来使用redirect_to

时间:2012-06-08 21:40:02

标签: ruby-on-rails ruby ruby-on-rails-3

我正在使用Rails 3,我在StatusController中有一个form_for。当我点击提交按钮时,我的创建方法永远不会被调用。我的create方法有一个redirect_to:index,但是当我点击提交时,所有信息都保留在表单中,并且页面不会重定向。但是,该对象可以在数据库中正确保存。

导致这种情况的原因是什么?

控制器:

class StatusController < ApplicationController
  def new
    @status = Status.new
  end
  def create
    @status = Status.new(params[:status])
    @status.date_added = Time.now
    if @status.save
    else
      render 'new'
    end
  end

查看:

.well
  =form_for @status do |f|
    =f.label :user_email
    =f.text_field :user_email

    =f.label :added_by
    =f.text_field :added_by

    =f.label :comments
    =f.text_area :comments
    %br
    %br
    =f.submit

我已经将代码调整为此,现在数据在提交时从表单中消失,但是对象永远不会被保存,因为“Create”永远不会被调用。

2 个答案:

答案 0 :(得分:0)

我刚刚在这里学习Ruby,所以我可能错了,但如果状态保存正确,看起来你永远不会重定向。

 class StatusController < ApplicationController
  def new
    @status = Status.new
  end
  def create
    @status = Status.new(params[:status])
    @status.date_added = Time.now
    if @status.save
      format.html { redirect_to @status } # Or :index if you want to redirect to index
    else
      render 'new'
    end
  end

当然,请确保您也创建了这些控制器方法和视图。

答案 1 :(得分:0)

你的控制器看起来有点奇怪...我假设你有Rails 3.2或更新。

class StatusController < ApplicationController
  respond_to :html

  def new
    @status = Status.new
  end
  def create
    @status = Status.new(params[:status])

    @status.date_added = Time.now
    @status.save
    respond_with(@status)
  end
end

respond_with为你做所有事情。如果保存失败,它会呈现new操作,如果保存成功,则会重定向到status_path(@status)。如果要更改重定向行为,可以使用(否则未记录的):location属性来阐明,您要在哪里重定向用户,或者您可以通过传递带有一个参数的块来覆盖默认的“成功”行为(格式) 。有关详细信息,请参阅its documentation

顺便说一句,如果您在状态迁移中使用t.timestamp,那么您已经拥有created_at字段,并且它由save / update_attributes方法自动处理,因此您可以执行此操作不需要date_added

相关问题