Question about re-using entry form when a validation error o


#1

Hi,

I think I may be doing more work than necessary. I have a form that is
used in both my “New” and “Edit” pages (originally created by a
scaffold.)

In my form, I have several popups that I have to populate, and if on
the Edit page, selects the appropriate entry.

To build the popup menus, I’m using:
<%= options_from_collection_for_select(@teams, “id”, “number”,
@match_teams[0]) %>

@teams is set in the controller New method:
@teams = Team.find(:all, :order => “number”)

and I have to set @match_teams to “”.

In the Edit method, I again have to set the @teams variable (no
problem), and I then set the @match_teams array like:

@match_teams = []
@match.competitions.each do |team|
  @match_teams << team.team_id
end

That’s fine. Except if the user enters an incorrect value into a field
(no duplicate “match” numbers, for example). The “Create” method does:
if @match.save

else
render :action => ‘new’ #error occured, re-display the form
end

However, when that happens, I get an error about having a null
variable on my form, in the first call to
‘options_from_collection_for_select’ - since @teams and @match_teams
is null.

So now I have to do:
@teams = Team.find(:all, :order => “number”)
@match_teams = []
params[:Red].each do |t|
@match_teams << t.to_i
end
params[:Blue].each do |t|
@match_teams << t.to_i
end

  render :action => 'new'

(pulling the user set values out of the form to re-set up the items).
And I realized I have to do the same thing in the “Update” method (if
it fails due to a validation fault.)

Am I missing something? Should the @teams and @match_teams variables
persist? Sure I can factor the similar code to its own method, but it
seems like a lot of extraneous work.

Thanks for any help / hints.

jt