Topic: Calling the same form multiple times

Hi,

I'm very new to rails and have the following question - I initially call a view with a :param from a link. After a save I would like to recall that same form - with the same :param - so that further input can be entered. It's not important to remember the previous input and I don't know how many times the form input will be carried out.

The controller in question looks like this...

class UnitController < ApplicationController
 
  scaffold :unit
 
  def new
    @unit = Unit.new
    @page_action = "Create new unit"   
    @army = Army.find_by_id(@params['army'] )
  end
 
  def create
    @unit = Unit.new(@params['unit'])
    if @unit.save
        redirect_to :action => 'new'
    else
        render_action 'new'
    end
  end
 
end

The view looks like this...

<h2>Army unit construction </h2>
<p>Army under construction <%=@army.name %></p>
<form action="/unit/create" method="post">
<input id="unit_army_id" name="unit[army_id]" size="5" type="hidden" value="<%=@army.id %>"/>
<p>
<b>Unit Abbreviation:</b><br/>
<input id="unit_myabbr" name="unit[myabbr]" size="5" type="text" value=""/>
</p>
  <b>Unit Description</b><br/>
<input id="unit_unitdesc" name="unit[unitdesc]" size="20" type="text" value=""/>

<p>Unit weight</p>
<%= select_tag "unit_weight", "<option>Light</option> <option>Medium</option> <option>Heavy</option>" %>

<input type="submit" value="Create"/>
</form>

Re: Calling the same form multiple times

It looks like you are doing things correctly by redirecting to the "new" action again when the "create" action succeeds. But from what I understand there are some parameters that the "new" action expects and you need to resend these same parameters? There are two possible solutions. One is to  call redirect_to :back like this:

  def create
    @unit = Unit.new(@params['unit'])
    if @unit.save
        redirect_to :back
    else
        render_action 'new'
    end
  end

However, the problem here is if the form validation fails one time, they fix the problem then resubmit the form, the "back" will actually go to the create action since that's what the last action was.

The proper way is to pass all of the paramters to he create action that you need in the new action, this way you can resend them when redirecting:

  def create
    @unit = Unit.new(@params['unit'])
    if @unit.save
        redirect_to :action => 'new', :foo => params[:foo]
    else
        render_action 'new'
    end
  end

If you need a more specific code example, I'll need the details on what parameters you are trying to pass.

Railscasts - Free Ruby on Rails Screencasts

Re: Calling the same form multiple times

Ryan,

Thanks for the pointer - that works as expected :-)

Steve.