1

我正在使用 Rails 3,并且在 StatusController 中有一个 form_for。当我点击提交按钮时,我的 create 方法永远不会被调用。我的 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

我已经对此进行了代码调整,现在数据在提交时从表单中消失了,但是该对象永远不会被保存,因为从未调用过“创建”。

4

2 回答 2

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属性来阐明您想要重定向用户的位置,或者您可以通过传递带有一个参数(格式)的块来覆盖默认的“成功”行为。有关更多信息,请参阅其文档

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

于 2013-08-29T14:48:20.387 回答
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

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

于 2012-06-08T22:07:00.353 回答