redirect_to 和 render 可以交换吗? [英] Are redirect_to and render exchangeable?

查看:39
本文介绍了redirect_to 和 render 可以交换吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于下面的代码,如果用 render 或 vise verse 替换 redirect_to 会发生什么?

def 创建@product = Product.new(params[:product])response_to do |格式|如果@product.saveformat.html { redirect_to(@product, :notice => '产品创建成功.') }别的format.html { 渲染:动作 =>新的" }结尾结尾结尾

在上面的代码中用另一个替换一个似乎没问题.是否有只需要使用 redirect_to 或 render 的地方?渲染除了渲染视图之外什么都不做.Redirect_to 向服务器发送 302 请求,重定向后当前参数丢失.

谢谢.

解决方案

如果你使用 render,当用户刷新页面时,它会再次提交之前的 POST 请求.这可能会导致重复购买等不良结果.

但是如果您使用 redirect_to,当用户刷新页面时,它只会再次请求相同的页面.这也称为.

For the code below, what happens if replacing redirect_to with render or vise verse?

def create
  @product = Product.new(params[:product])

  respond_to do |format|
    if @product.save
      format.html { redirect_to(@product, :notice => 'Product was successfully created.') }

    else
      format.html { render :action => "new" }
    end
  end
end

It seems OK replacing one with the other in code above. Is there a place where only redirect_to or render has to be used? Render does nothing but rendering a view. Redirect_to sends 302 request to server and current parameters are lost after redirecting.

Thanks.

解决方案

If you're using render, when the user refreshes the page, it will submit the previous POST request again. This may cause undesired results like duplicate purchase and others.

But if you're using redirect_to, when the user refreshes the page, it will just request that same page again. This is also known as the Post/Redirect/Get (PRG) pattern.

So the place where redirect_to should be used is when you're doing a HTTP POST request and you don't want the user to resubmit the request when it's done (which may cause duplicate items and other problems).

In Rails, when a model fails to be saved, render is used to redisplay the form with the same entries that was filled previously. This is simpler because if you use redirect, you'll have to pass the form entries either using parameters or session. The side effect is that if you refresh the browser, it will try to resubmit the previous form entries. This is acceptable because it will probably fail the same way, or if it's successful now, it was what the user should expect in the first place anyway.

For more in depth explanation about render and redirect, you should read this article.

这篇关于redirect_to 和 render 可以交换吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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