Rails:通过表单创建新记录时验证失败后的 URL [英] Rails: URL after validation fails when creating new records via form

查看:19
本文介绍了Rails:通过表单创建新记录时验证失败后的 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在使用一个表单和一个标准的 Rails restful 控制器创建一个新的 Foo,它看起来像这样:

Lets say I am creating a new Foo using a form and a standard Rails restful controller, which looks something like this:

class FoosController < ApplicationController
  ...
  def index
    @foos = Foo.all
  end

  def new
    @foo = Foo.new
  end

  def create
    @foo = Foo.create(params[:foo])
    if @foo.save
      redirect_to foos_path, :notice => 'Created a foo.'
    else
      render 'new'
    end
  end
  ...
end

因此,如果我使用标准的 restful 控制器(如上所述),那么当我创建 Foo 时,我位于 example.com/foos/new,并且如果我提交表单并它正确保存我在 example.com/foos 显示索引操作.但是,如果表单未正确填写,表单将再次呈现并显示错误消息.这都是普通的香草.

So, if I use the standard restful controller (as above), then when I'm creating the Foo I am at example.com/foos/new, and if I submit the form and it saves correctly I'm at example.com/foos showing the index action. However, if the form is not filled correctly the form is rendered again and error messages are shown. This is all plain vanilla.

但是,如果显示错误,将呈现表单页面,但 URL 将是 example.com/foos,因为 CREATE 操作会发布到该 URL.但是,人们希望在 example.com/foos 上找到 Foos#index,而不是他们现在刚刚提交并添加了错误消息的表单.

However, if errors are shown, the form page will be rendered but the URL will be example.com/foos, because the CREATE action posts to that url. However, one would expect to find Foos#index at example.com/foos, not the form they just submitted now with error messages added.

这似乎是 Rails 的标准行为,但对我来说没有多大意义.显然我可以重定向回 new 而不是从 create 操作呈现 new,但问题是错误消息等会随着内存中部分完整的 Foos 一起丢失.

This seems to be Rails standard behavior, but it doesn't make a lot of sense to me. Obviously I could redirect back to new instead of rendering new from the create action, but the problem with that is the error messages etc. would be lost along with the partially complete Foos in memory.

对于这个问题,是否有一个干净的解决方案,当他们提交的新 Foo 表单中有错误时,一种将人们送回 example.com/foos/new 的方法?

Is there a clean solution for this problem, a way to send people back to example.com/foos/new when there are errors in the new Foo form they submitted?

谢谢!

推荐答案

您可以通过在初始化程序中添加以下内容来挂钩 Rails 路由:https://gist.github.com/903411

You could hook into rails routing by adding this in an initializer: https://gist.github.com/903411

然后只需将常规资源放在您的 routes.rb 中:

Then just put the regular resources in your routes.rb:

resources :users

它应该创建您正在寻找的路由和行为.

It should create the routes and behaviour you are looking for.

这篇关于Rails:通过表单创建新记录时验证失败后的 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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