在 Rails 中发布重定向获取模式 [英] Post Redirect Get pattern in Rails

查看:45
本文介绍了在 Rails 中发布重定向获取模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Rails 中实现 PRG?

How can I implement PRG in Rails?

我在 Rails 中使用了 PRG,但我并不完全相信它是正确的.我想知道在 Rails 中是否有更好的方法来处理它?<​​/p>

I used PRG in Rails, but I am not totally convinced it's right. I was wondering is there any better way to handle it in Rails?

推荐答案

我不知道 PRG 模式有多流行,以及为什么人们必须虔诚地坚持重定向"来解决它的失败方面(实际上,一个很好的理由有时您不想处理创建失败时的设置"复杂性并保持干燥).

I don't know how popular PRG pattern is and why one has to religiously stick to the "redirect" on failure aspect of it (actually, one good reason is sometimes you dont want to deal with the "setup" complexity at create failure and keep things dry).

您基本上需要的是将 :user 的参数转移到新的.我认为上面@Hitesh 的解决方案非常接近.

What you basically need is to transfer the params for :user to new. I think @Hitesh's solution above is quite close.

class UsersController < ApplicationController

  def new
    if flash[:user_params]
      @user = User.new(flash[:user_params])
      @user.valid?
    else
      @user = User.new
    end
  end

  def create
    @user = User.new(params[:user])

    if @user.save
      # clears previously stored user if there is any
      flash[:notice] = "User created."
      redirect_to '/'
    else
      flash[:error] = "Error saving User"
      flash[:user_params] = params[:user]
      redirect_to :action => :new
    end
  end
end

这篇关于在 Rails 中发布重定向获取模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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