【问题标题】:rails form_for never invokes the create controller action to use redirect_torails form_for 从不调用创建控制器操作来使用 redirect_to
【发布时间】:2012-06-08 21:40:01
【问题描述】:

我正在使用 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

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

【问题讨论】:

  • @Goober 您应该发布新的代码并从状态控制器创建操作以及来自“新”视图的 form_for 代码。
  • 其实你的create方法没有redirect_to :index
  • 您的状态模型中是否有任何可能导致此问题的验证?
  • 如果确实没有调用 create 操作,可能是路由问题。您的 routes.rb 中有 resources :statuses 吗?
  • 感谢 cdesrosiers,我是个白痴...将控制器生成为 StatusController 而不是 StatusesController。难怪一切都崩溃了。

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


【解决方案1】:

我只是在这里学习 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

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

【讨论】:

  • 你错过了respond_to 块...我的眼睛扔了NoMethodError: undefined method 'format' for main:Object :-)
【解决方案2】:

你的控制器看起来有点奇怪......我假设你有 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.timestamps,那么你已经有created_at字段,它由save/update_attributes方法自动处理,所以你不需要date_added

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多