views:

84

answers:

1

I'm working on a relatively simple website with (currently) a single resource. I have a form at GET /maps/new that submits data for a new Map to POST /maps, which redirects to GET /maps/:id after completion. The problem here is that if validation fails, it renders the new-map form, so the URL is still /maps. But redirecting to /maps/new loses the validation errors (and map data they previously entered).

This is my first real Rails-based website, so I'm sure this is probably something basic I'm missing. Here are my new and create actions, both pretty much unchanged from the generated scaffolding:

def new
  @map = Map.new

  respond_to do |format|
    format.html # new.html.erb
    format.xml  { render :xml => @map }
  end
end

def create
  @map = Map.new(params[:map])

  respond_to do |format|
    if @map.save
      flash[:notice] = 'Map was successfully created.'
      format.html { redirect_to(@map) }
      format.xml  { render :xml => @map, :status => :created, :location => @map }
    else
      format.html { render :action => 'new' }
      format.xml  { render :xml => @map.errors, :status => :unprocessable_entity }
    end
  end
end

How can I get the URL to remain on /maps/new for the form, yet also maintain the intermediate form data and errors?

A: 

Does this work for you?

def new
  @map = flash[:map] || Map.new

...

 else
   flash[:map] = @map
   format.html { redirect_to new_map_url }
Andy Gaskell
It does! Thank you very much!
Twisol
Scratch that, it doesn't work when I try to save a real Map object like that: I get a cookie overflow error. Under normal circumstances, a cookie overflow would be wonderful, but... The search continues.
Twisol
The problem is the size of that object is over 2k. You could switch to the p_store or active record for storing your sessions.
Andy Gaskell
It works now, all I had to do was uncomment a line in the session_store.rb initializer, run rake db:sessions:create and db:migrate, and cut down the session secret key so that it actually fit into the session table. Thanks!
Twisol