在Rails中,当资源创建操作失败并调用render:new时,为什么URL必须更改为资源的索引URL? [英] In Rails when a resource create action fails and calls render :new, why must the URL change to the resource's index url?

查看:89
本文介绍了在Rails中,当资源创建操作失败并调用render:new时,为什么URL必须更改为资源的索引URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Books的资源。

I have a resource called Books. It's listed as a resource properly in my routes file.

我有一个新操作,该操作为新视图提供了标准:

I have a new action, which gives the new view the standard:

@book = Book.new

开在模型中,有一些属性可以通过状态进行验证,因此,如果保存操作失败,则会生成错误。

On the model, there are some attributes which are validated by presence, so if a save action fails, errors will be generated.

在我的控制器中:

@book = Book.create
...  # some logic
if @book.save
  redirect_to(@book)
else
  render :new
end

这是相当标准以及使用render:new的原理是这样,以便将对象传递回视图并可以报告错误,重新填写表单条目等。

This is pretty standard; and the rationale for using render:new is so that the object is passed back to the view and errors can be reported, form entries re-filled, etc.

,除了每次(通过render:new)发送回表单时,都会显示我的错误,但是我的URL是INDEX URL,即

This works, except every time I'm sent back to the form (via render :new), my errors show up, but my URL is the INDEX URL, which is

/books

而不是

/books/new

我首先开始的地方。我看过其他一些有关此问题的帖子,但没有答案。至少,有人会假设它会把您放在/ books / create,我也有一个查看文件(在这种情况下,与new相同)。

Which is where I started out in the first place. I have seen several others posts about this problem, but no answers. At a minimum, one would assume it would land you at /books/create, which I also have a view file for (identical to new in this case).

我可以这样做:

# if the book isn't saved then
flash[:error] = "Errors!"
redirect_to new_book_path

但是随后@book数据以及错误消息都丢失了,

But then the @book data is lost, along with the error messages, which is the entire point of having the form and the actions, etc.

为什么渲染:new使我进入/ books,我的索引动作,通常该URL会调用INDEX方法,其中列出了所有书籍?

Why is render :new landing me at /books, my index action, when normally that URL calls the INDEX method, which lists all the books?

推荐答案

实际上将您发送到创建路径。它在 create 操作中,使用HTTP方法POST的路径为 / books 。这看起来与索引路径 / books 相同,但是索引路径使用的是HTTP方法GET。在确定调用哪个动作时,rails路由代码会考虑该方法。验证失败后,您仍处于create动作中,但正在呈现 new 视图。有点令人困惑,但是 render:new 这样的行实际上根本没有调用新操作;它仍在运行create操作,并告诉Rails渲染新的 view

It actually is sending you to the create path. It's in the create action, the path for which is /books, using HTTP method POST. This looks the same as the index path /books, but the index path is using HTTP method GET. The rails routing code takes the method into account when determining which action to call. After validation fails, you're still in the create action, but you're rendering the new view. It's a bit confusing, but a line like render :new doesn't actually invoke the new action at all; it's still running the create action and it tells Rails to render the new view.

这篇关于在Rails中,当资源创建操作失败并调用render:new时,为什么URL必须更改为资源的索引URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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