kazimanzurrashid kazimanzurrashid - 4 months ago 21
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

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