rails form_for 从不调用创建控制器操作来使用 redirect_to [英] rails form_for never invokes the create controller action to use redirect_to

查看:43
本文介绍了rails form_for 从不调用创建控制器操作来使用 redirect_to的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Rails 3, and I have a form_for in a StatusController. When I hit the submit button, my create method is never called. My create method has a redirect_to :index, however when I hit submit all of the information remains in the form, and the page does not redirect. The object does save correctly in the database however.

这是什么原因造成的?

控制器:

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

我已经将代码调整为这个,现在提交时数据从表单中消失,但是对象永远不会被保存,因为创建"永远不会被调用.

I've adjusted the code to this, and now the data disappears from the form upon a submit, however the object never gets saved because "Create" is never invoked.

推荐答案

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

Your controller looks like a bit weird... I assume you have Rails 3.2 or newer.

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 属性来阐明您要将用户重定向到何处,或者您可以通过传递一个块来覆盖默认的成功"行为参数(格式).有关详细信息,请参阅其文档.

respond_with is do all things for you. It renders new action if saving fails, and redirects to status_path(@status) if saving succeeds. If you want to change redirection behavior, you can use (otherwise undocumented) :location attribute to clarify, where you want to redirect user, or you can overwrite default "success" behavior by passing a block with one argument (format). See its documentation for more info.

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

Btw, if you use t.timestamps in status's migration, then you already have created_at field and it is handled automatically by save/update_attributes methods, so you do not need date_added.

这篇关于rails form_for 从不调用创建控制器操作来使用 redirect_to的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆