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?
Use the session, Luke
The way you implemented it in your blog post is quite fine, however you may want to use session
instead of flash
to store your @user
and optionally use the ActiveRecord session store to keep cookies from getting bloated.
ActiveRecord::SessionStore - Sessions are stored in your database, which works better than PStore with multiple app servers and, unlike CookieStore, hides your session contents from the user. To use ActiveRecord::SessionStore, set
config.action_controller.session_store = :active_record_store
in your
config/environment.rb
and runrake db:sessions:create
.
So you should…
class UsersController < ApplicationController
def new
@user = session[:user] || User.new
end
def create
@user = User.new(params[:user])
if @user.save
# clears previously stored user if there is any
session[:user] = nil
redirect_to '/'
else
session[:user] = @user
redirect_to :action => :new
end
end
end