kazimanzurrashid kazimanzurrashid - 1 year ago 97
Ruby Question

Post Redirect Get pattern in Rails

How can I implement PRG in Rails?

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?

Answer Source

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).

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 = User.new

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

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